我正在尝试使用我的应用程序中的Java Mail API发送电子邮件。我使用的代码如下:
private void sendMail(Properties props, String fromEmail, String password, String toEmail, String messageSubject, String messageBody)
{
final String username = fromEmail;
final String pasword = password;
//props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username,pasword);
}
});
try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toEmail));
message.setSubject(messageSubject);
message.setText(messageBody);
Transport.send(message);
}
catch (MessagingException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
}
我有以下属性:
{mail.smtp.port=587, mail.smtp.socketFactory.port=465, mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory, mail.smtp.auth=true, mail.smtp.host=smtp.office365.com}
我收到以下异常:
Caused by: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
相同的代码适用于smtp.gmail.com
,我可以通过基于gmail的电子邮件发送邮件。是否有解决此问题的方法。
答案 0 :(得分:0)
删除身份验证器,然后按Transport.send method that takes a username and password中所述调用JavaMail FAQ。
答案 1 :(得分:0)
请在代码中设置以下内容
message.setHeader("X-Mailer","your application name");