【发布时间】:2019-04-20 01:53:14
【问题描述】:
我想从我的 java(JSP) 项目(基本上是一个基于 Web 的项目)向用户发送邮件。 但我遇到了一个错误。给我解决方案。
我尝试了很多网上提供的解决方案,但没有任何解决办法。 我将端口号 465 更改为 587,但我的错误仍然存在。
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailUtil {
private String from1 = "fromemail@gmail.com";
private String password= "*****";
private String FROM_NAME = "abc";
public boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message) {
try {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
// props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.debug", "false");
props.put("mail.smtp.ssl.enable", "true");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from1, password);
}
});
Message msg = new MimeMessage(session);
InternetAddress from = new InternetAddress(from, name);
msg.setFrom(from);
InternetAddress[] toAddresses = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
toAddresses[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, toAddresses);
InternetAddress[] bccAddresses = new InternetAddress[bccRecipients.length];
for (int j = 0; j < bccRecipients.length; j++) {
bccAddresses[j] = new InternetAddress(bccRecipients[j]);
}
msg.setRecipients(Message.RecipientType.BCC, bccAddresses);
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
return true;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
return false;
} catch (MessagingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
}
}
严重:无
javax.mail.SendFailedException:发送失败; 嵌套异常是: class javax.mail.MessagingException: 530 5.7.0 必须先发出 STARTTLS 命令。 d129sm8507654pfa.142 - gsmtp
at javax.mail.Transport.send0(Transport.java:218)
at javax.mail.Transport.send(Transport.java:80)
【问题讨论】:
-
如果问题仍然存在,据我所知,您应该打开“允许您的 Gmail 帐户使用安全性较低的应用程序”
标签: java jsp tomcat jakarta-mail