public static String name = "xxx@163.com"; public static String pwd = "xxx";//授权码 在163里申请 public static String host = "smtp.163.com"; public static String portData = "25";
这里操作完成申请授权码
public static void mailProperties(String to, String subject, String msgBody) {
Properties properties = System.getProperties(); //获取系统属性,主要用于设置邮件相关的参数。
properties.setProperty("mail.smtp.host", host);//发件人邮箱服务地址
properties.setProperty("mail.smtp.port", portData);//ssl端口
properties.setProperty("mail.smtp.auth", "true");//用户验证并返回Session,开启用户验证,设置发送邮箱的账号密码。
properties.setProperty("mail.transport.protocol", "smtp");//使用协议
properties.setProperty("mail.smtp.ssl.enable", "true");//使用协议
MailAuthenticator mailAuthenticator = new MailAuthenticator(name, pwd);
Session session1 = Session.getInstance(properties, mailAuthenticator); //1、创建session
session1.setDebug(true);
session1.setDebugOut(System.out);
try {
MimeMessage message = new MimeMessage(session1); //4、创建邮件
message.setFrom(new InternetAddress(name)); //发件人
try {
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to, "你好,收到一封邮件", "UTF-8"));//收件人//MimeMessage.RecipientType.TO:发送、CC:抄送BCC:密送
} catch (Exception e) {
e.printStackTrace();
}
message.setSubject(subject, "UTF-8");
message.setContent(msgBody, "text/html;charset=UTF-8");
// Transport transport = session1.getTransport(); //2、通过session得到transport对象
Transport transport = session1.getTransport("smtp");
// transport.connect(name,pwd);
transport.connect();//3、使用邮箱的用户名和密码连上邮件服务器
transport.sendMessage(message, message.getAllRecipients());//5、发送邮件
transport.close();
System.out.println("发送成功!");
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static class MailAuthenticator extends Authenticator {
private String strUser;
private String strPwd;
public MailAuthenticator() {
super();
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = this.strUser;
String password = this.strPwd;
if ((username != null) && (username.length() > 0) && (password != null) && (password.length() > 0)) {
return new PasswordAuthentication(username, password);
}
return null;
}
public MailAuthenticator(String user, String password) {
this.strUser = user;
this.strPwd = password;
}
}