配置setting.json
为下载的mail.jar包,activation.jar包找个家,不需要手动添加到classpath环境变量。
邮件发送源码
用QQ邮箱发送,主要有两个点,一是获取授权码
二是发送,需要实现认证行为类实现作为Session保持会话
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendHtmlEmail {
public static void main(String[] args) {
String to = "920061142@163.com";
String from = "pardon110@qq.com";
String host = "smtp.qq.com";
// qq授权码
String code = "gkf**g";
Properties props = System.getProperties();
// 设置邮件服务器
props.setProperty("mail.smtp.host", host);
props.put("mail.smtp.port", 465);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.auth", true);
// 获取默认的 Session 对象,帐号密码验证使用匿名类
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, code);
}
});
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("来自pardon110的邮件");
// 消息体为html
msg.setContent("<h1>This is actual message</h1>html", "text/html");
// 使用类对象的静态方法发送
Transport.send(msg);
System.out.println("Sent html successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
msg引用了session,session含认证信息,邮件发送使用的是Transport对象的静态方法send。
若前期session未包含认证信息,需要在使用Transport实例的sendmsg方法,且在实例之前建立连接时带上认证信息亦可,见Transport实例发件