如果发件邮箱是qq邮箱,需要设置SSL加密,MAIL_PASSWORD为qq邮箱的16位授权码。如果发件邮箱是其他普通邮箱,则不设置SSL加密,MAIL_PASSWORD为发件邮箱密码。
public void sendMail(String subject, String content, String receiver) {
try {
log.info("接收人邮箱receiver={}", receiver);
//创建一个配置文件并保存
Properties properties = new Properties();
//发件邮箱主机地址
properties.setProperty("mail.host",MAIL_HOST);
properties.setProperty("mail.transport.protocol","smtp");
//发件邮箱主机端口
properties.setProperty("mail.smtp.port",MAIL_PORT);
properties.setProperty("mail.smtp.auth","true");
log.info("发件服务器为{}:{}", MAIL_HOST, MAIL_PORT);
//设置SSL加密
if (isSSL){
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
}
//创建一个session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MAIL_USER,MAIL_PASSWORD);
}
});
log.info("发件人邮箱账号密码{}/{}", MAIL_USER, MAIL_PASSWORD);
//开启debug模式
session.setDebug("true".equals(MAIL_DEBUG));
//获取连接对象
Transport transport = session.getTransport();
//连接服务器
transport.connect();
//创建邮件对象
MimeMessage mimeMessage = new MimeMessage(session);
//邮件发送人
mimeMessage.setFrom(new InternetAddress(MAIL_USER));
//邮件接收人
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(receiver));
//邮件标题
mimeMessage.setSubject(subject);
//邮件内容
mimeMessage.setContent(content,"text/html;charset=UTF-8");
//发送邮件
transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
//关闭连接
transport.close();
log.info("邮件发送成功");
}catch (Exception e){
log.error("邮件发送异常");
}
}
本文介绍如何使用Java编程语言通过SMTP协议发送电子邮件,包括设置SSL加密以提高安全性,特别关注使用QQ邮箱作为发件邮箱的情况。文章详细解释了如何根据发件邮箱类型(QQ邮箱或其他普通邮箱)调整配置参数,以及如何使用16位授权码或邮箱密码进行身份验证。
1719

被折叠的 条评论
为什么被折叠?



