我正在尝试在调用此方法的java应用程序中发送电子邮件:
File::makeDirectory(public_path('storage/uploads/albums/'.$name));
但由于某些原因,当调试遇到Transport.send()时,我遇到了这个异常:
public static void sendEmail() {
// Create object of Property file
Properties props = new Properties();
// this will set host of server- you can change based on your requirement
props.put("mail.smtp.host", "smtp.office365.com");
// set the port of socket factory
//props.put("mail.smtp.socketFactory.port", "587");
// set socket factory
//props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
// set the authentication to true
props.put("mail.smtp.auth", "true");
// set the port of SMTP server
props.put("mail.smtp.port", "587");
// This will handle the complete authentication
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xx@mail.com", "xx");
}
});
try {
// Create object of MimeMessage class
Message message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress("xx@mail.com"));
// Set the recipient address
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("yy@mail.com"));
// Add the subject link
message.setSubject("Testing Subject");
// Create object to add multimedia type content
BodyPart messageBodyPart1 = new MimeBodyPart();
// Set the body of email
messageBodyPart1.setText("This is message body");
// Create object of MimeMultipart class
Multipart multipart = new MimeMultipart();
// add body part 2
multipart.addBodyPart(messageBodyPart1);
// set the content
message.setContent(multipart);
// finally send the email
Transport.send(message);
System.out.println("=====Email Sent=====");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
为什么即使我使用了Authenticator()?
也会发生这种情况答案 0 :(得分:2)
如果通过端口587连接,则最初启动普通连接,必须通过显式发送STARTTLS命令启动TLS。您必须告诉JavaMail这样做,否则它将尝试进行不安全的操作。除非建立了TLS连接,否则SMTP服务器不会发送任何身份验证机制信息,因此JavaMail假定不需要身份验证并尝试不发送邮件。
将以下条目添加到属性中:
props.put("mail.smtp.starttls.enable", "true");
在尝试进行身份验证之前,JavaMail应该尝试切换到TLS。
如果失败,您需要通过设置属性
启用调试props.put("mail.debug", "true");a
并在此处发布输出。