Java发送邮件:javax.mail.AuthenticationFailedException

时间:2019-02-21 09:57:03

标签: java authentication javamail

我试图从Java应用程序发送邮件。我没有使用任何身份验证,因为身份验证后我已经将发件人地址存储在数据库中。这是计划发送的电子邮件,因此发送邮件时我无法获取密码。因此,我首先在身份验证后将电子邮件ID存储在表中,然后再安排电子邮件。 请检查以下代码

public void sendMessage(EmailMessage emailMessage) {
    Properties props = mailConfiguration.getProps();
    Session session = Session.getInstance(props);
    MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(emailMessage.getFromAddress()));
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(emailMessage.getToAddress()));
        mimeMessage.setSubject(emailMessage.getSubject());
        mimeMessage.setContent(emailMessage.getMessage(), "text/html");
        mimeMessage.setSentDate(new Date());
        Transport.send(mimeMessage);
        LocalDateTime localDateTime = LocalDateTime.now();
        Timestamp sendTime = Timestamp.valueOf(localDateTime);
        emailMessage.setGeneratedTime(sendTime);
        emailMessage.setStatus(MessageStatus.SENT);
    } catch (AuthenticationFailedException e) {
        log.error("Username and Password not accepted." + e.getMessage(), e);
        emailMessage.setStatus(MessageStatus.ERROR);
    } catch (MessagingException e) {
        log.error("An exception occurred while sending mail from [" + emailMessage.getFromAddress() + "] to [" + emailMessage.getToAddress() + "] : " + e.getMessage(), e);
        emailMessage.setStatus(MessageStatus.ERROR);
    }
    log.info("Changing message status of Email Message " + emailMessage.getId() + " to " + emailMessage.getStatus());
    emailMessageRepository.save(emailMessage);
}

电子邮件配置看起来像

@Configuration
public class MailConfiguration {

Properties props = new Properties();

 public MailConfiguration() {
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.starttls.required", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    props.put("mail.debug", "false");
 }

 public Properties getProps() {
    return props;
 }
}

问题是我无法使用此发送电子邮件。相反,我得到了

这样的异常
  

javax.mail.AuthenticationFailedException:空

出什么问题了? 我在这里搜索了几乎类似的问题。但是他们没有解释我的情况

1 个答案:

答案 0 :(得分:0)

您需要进行身份验证。在数据库中存储“发件人”地址还不够。