javamail发送Gmail报错

wangluoyu wangluoyu 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
最近写的一个Gmail邮件发送程序,本地发送正常,一上线就发不出去,报错信息如下:
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.AuthenticationFailedException
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
at com.util.mail.SendGMail.sendMail(SendGMail.java:70)
环境为linux+tomcat,
源码如下:

public class SendGMail {
/**
* 设置一些使用属性
*/
private static final String MAIL_CONTENT_TYPE = "text/html;charset=utf-8";

/**
* 设置Properties
*/
private static final String MAIL_SMTP_HOST = "smtp.gmail.com"; // 这是gmail的smtp服务器域名
private static final String MAIL_SMTP_PORT = "465"; // 注意:gmail的smtp服务器使用的是465端口
private static final String MAIL_SMTP_AUTH = "true";
private static final String MAIL_SMTP_SOCKETFACTORY_CLASS = "javax.net.ssl.SSLSocketFactory";
private static final String MAIL_SMTP_SOCKETFACTORY_FALLBACK = "false";
private static final String MAIL_SMTP_SOCKETFACTORY_PORT = "465";
private static final String MAIL_SMTP_SSL = "true";

public static void sendMail(String toEmail,String subject,String content) {
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", MAIL_SMTP_HOST);
props.setProperty("mail.smtp.socketFactory.class", MAIL_SMTP_SOCKETFACTORY_CLASS);
props.setProperty("mail.smtp.socketFactory.fallback", MAIL_SMTP_SOCKETFACTORY_FALLBACK);
props.setProperty("mail.smtp.port", MAIL_SMTP_PORT);
props.setProperty("mail.smtp.socketFactory.port", MAIL_SMTP_SOCKETFACTORY_PORT);
props.setProperty("mail.smtp.auth", MAIL_SMTP_AUTH);
props.setProperty("mail.smtp.ssl", MAIL_SMTP_SSL);
props.put("mail.smtp.debug", "true");

Session session = Session.getDefaultInstance(props, new Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(SysType.GMAIL_CONFIG[0], SysType.GMAIL_CONFIG[1]);
}
});

// create a new message
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(SysType.GMAIL_CONFIG[0]));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject(subject);

/** 设置邮件内容 */
Multipart multipart = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(content, MAIL_CONTENT_TYPE);
multipart.addBodyPart(bodyPart);

message.setContent(multipart);
message.setSentDate(new java.util.Date());
message.saveChanges();

Transport.send(message);
} catch(MessagingException ex) {
ex.printStackTrace();
}
}

public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append("test");
String toEmail = "00000000000@qq.com";
String subject = "test";
SendGMail.sendMail(toEmail,subject,sb.toString());
System.out.println("OK");
}
}

不知道是哪里有问题,盼各位大虾指教。
...全文

相关推荐

评论 4
收藏 已收藏
分享
返回顶部
wangluoyu
Java EE 67,535 成员 225,843 内容