我想从我的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:发送失败; 嵌套的异常是: 类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)