使用Java Mail API。 javax.mail.MessagingException:无法确定本地电子邮件地址异常

时间:2019-02-20 13:00:29

标签: java email javamail

我正在使用Java Mail API,并且在本地计算机上运行良好,但是当我在服务器上部署Web应用程序时,出现了异常,提示javax.mail.MessagingException:无法确定本地电子邮件地址。

这是我的代码

Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    try {
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("fromEmailAdd@gmail.com", "fromEmailPass");
        }
    });

        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@gmail.com"));
        message.setSubject("sub");
        message.setText("msg");    
        Transport.send(message);

        System.out.println("mail sent successfully");
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);

    }

下面给出的是此代码引发的异常。

  

javax.mail.MessagingException:无法确定本地电子邮件地址

2 个答案:

答案 0 :(得分:0)

该消息说“本地电子邮件地址丢失”,这意味着发件人的电子邮件地址丢失。我认为您可以尝试执行以下操作:

JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("mail.host.com")

MimeMessage message = sender.createMimeMessage();

MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setFrom("from@from.address");
helper.setTo("to@to.com");
helper.setText("testing text");

答案 1 :(得分:0)

从这个问题: Failed messages: javax.mail.MessagingException: can't determine local email address

作者似乎建议未设置发件人地址时抛出此异常。

MimeMessage message = new MimeMessage(session);
message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@gmail.com"));
message.setFrom("from@gmail.com"); // <-- add 'from' email address
message.setSubject("sub");
message.setText("msg");    
Transport.send(message);