package com.jetair.testSendMail;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;
/**
* Created by 22431 on 2016/8/22.
*/
public class SendMail {
public static void main(String[] args) throws MessagingException {
new SendMail().run();
}
public void run() {
// 跟smtp服务器建立一个连接
Properties prop = new Properties();
// 设置邮件服务器主机名
prop.setProperty("mail.host", "smtp.qq.com");// 指定邮件服务器,默认端口 25
// 发送服务器需要身份验证
prop.setProperty("mail.smtp.auth", "true");// 要采用指定用户名密码的方式去认证
// 发送邮件协议名称
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.timeout" , "80000");
// 开启SSL加密,否则会失败
MailSSLSocketFactory mailSSLSocketFactory = null;
try {
mailSSLSocketFactory = new MailSSLSocketFactory();
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
}
mailSSLSocketFactory.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
// 开启debug调试,以便在控制台查看
// session.setDebug(true);也可以这样设置
// p.setProperty("mail.debug", "true");
// 创建session
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名可以用QQ账号也可以用邮箱的别名
PasswordAuthentication pa = new PasswordAuthentication(
"2243146624", "gitdldtsbropdiag");
// 后面的字符是授权码,用qq密码不行!!
return pa;
}
});
session.setDebug(true);// 设置打开调试状态
try {
// 声明一个Message对象(代表一封邮件),从session中创建
MimeMessage msg = new MimeMessage(session);
// 邮件信息封装
// 1发件人
msg.setFrom(new InternetAddress("2243146624@qq.com"));
// 2收件人
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("mr_hongxinzhu@163.com"));
// 3邮件内容:主题、内容
msg.setSubject( "测试sendMail");
// msg.setContent("<a href=" ">go</a>", "text/html;charset=utf-8");// 发html格式的文本
msg.setText("这只是一个测试,真的就只是一个测试");
// 发送动作
Transport.send(msg);
System.out.println("发送邮件成功");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
sendMail
最新推荐文章于 2022-10-26 09:23:06 发布