我正在研究 Java Spring、Maven,我正在尝试使用 gmail id 在 gmail 上发送邮件。我收到此错误:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. 11sm885884pfp.38 - gsmtp
即使我已经设置了参数
mail.smtp.starttls.enable
为真。
这是我的功能:
public String sendMail(String to, String subject, String textMessage) throws IOException {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
Session mailSession = Session.getInstance(props);
mailSession.setDebug(true);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = from@gmail.com;
InternetAddress toAddress = null;
try {
toAddress = new InternetAddress(to);
} catch (AddressException e) {
System.out.print("\nError in Address of Sender or reciever\n");
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(textMessage);
SMTPTransport t = (SMTPTransport) mailSession.getTransport("smtp");
t.setStartTLS(true);
t.connect("smtp.gmail.com", "from@gmail.com", "from.password!");
t.sendMessage(simpleMessage, simpleMessage.getAllRecipients());
t.close();
} catch (MessagingException e) {
System.out.print("\nError in message Genration\n");
e.printStackTrace();
}
return "success";
}
SO 上的所有答案都告诉我们将 mail.smtp.starttls.enable 设置为 true。这样做甚至不起作用。
我还在我的 pom 中包含了 javax.mail 依赖项:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>