javamail发送Gmail报错
最近写的一个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");
}
}
不知道是哪里有问题,盼各位大虾指教。