javamail邮件发送

时间:2023-03-09 02:10:41
javamail邮件发送

// 发送邮件
public static void send(String toEmail, String content) {
Session session = getSession();
try {
System.out.println("--send--" + content);
// Instantiate a message
Message msg = new MimeMessage(session); // Set message attributes
msg.setFrom(new InternetAddress("from@qq.com"));//发件人地址
InternetAddress[] address = { new InternetAddress("to@qq.com") };
msg.setRecipients(Message.RecipientType.TO, address);// 收件人地址
msg.setSubject("这是发生的主题");// 发送的主题
msg.setSentDate(new Date());// 发送日期
msg.setContent("这是发生的内容", "text/html;charset=utf-8");// 发送类型 // Send the message
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
}
} private static Session getSession() {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.qq.com");// 设置服务器地址
props.put("mail.store.protocol", "smtp");// 设置协议
props.put("mail.smtp.port", 25);// 设置端口
props.put("mail.smtp.auth", "true");// 一定要这么设置,验证"true",不能设置为true
// 创建一个密码验证器
Authenticator authenticator = new Authenticator() { @Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("from@qq.com", "****");//发送邮件的账户和密码
} };
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session session = Session.getDefaultInstance(props, authenticator); return session;
}

我用的是mail.jar和activation-1.1.1.jar。

发送者邮箱需要开启POP3/SMTP服务和IMAP/SMTP服务。qq邮箱发送,设置服务的时候需要设置独立密码,上面使用的验证密码就是这个独立密码,使用qq邮箱的登录密码是不行的。否则会报:535 Authentication failed 这个错误。

调用上面的send方法,把要接受邮箱的地址和内容传过来就可以。