[Java] 纯文本查看 复制代码
public class MailUtils2 {
private static String smtp_host ="smtp.qq.com"; // QQ SMTP服务
private static String username = "使用发件人邮箱地址"; // 邮箱账户
private static String password = "iiotqaasiaiabfgc"; // 邮箱授权码-该授权码就是在开启QQPOP3/SMTP服务时返回的那串激活码
private static String from = "使用发件人邮箱地址"; // 邮箱账户
public static void sendMail(String subject, String content, String to) {
//设置发送邮件的properties
Properties props = new Properties();
props.setProperty("mail.smtp.host", smtp_host);
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.auth", "true");
// QQ 邮箱需要 SSL 加密
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
//准备连接对象
Session session = Session.getInstance(props);
//创建邮件信息
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));//设置发件人
message.setRecipient(RecipientType.TO, new InternetAddress(to));//设置收件人以及收件人地址
message.setSubject(subject);//邮件主题
message.setContent(content, "text/html;charset=utf-8");//支持富文本内容
Transport transport = session.getTransport();
transport.connect(smtp_host, username, password);
transport.sendMessage(message, message.getAllRecipients());//发送邮件
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("邮件发送失败...");
}
}
public static void main(String[] args) {
//测试
sendMail("测试邮件", "你好a", "收件人邮箱地址");
}
}