javax.mail指定的地址不用于发送邮件

时间:2021-10-22 18:17:28

I'm trying to send email from my Java code. I'm using the javax.mail library. This is my code:

我正在尝试从我的Java代码发送电子邮件。我正在使用javax.mail库。这是我的代码:

public class SendMail {

public void postMail(final String recipients, final String subject, final String message) throws MessagingException {
    boolean debug = false;
    java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "gmail-smtp.l.google.com");
    props.put("mail.smtp.auth", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    session.setDebug(debug);
    try {

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress("me@gmail.com");
        msg.setFrom(addressFrom);
        InternetAddress addressTo = new InternetAddress(recipients);
        msg.setRecipient(Message.RecipientType.TO, addressTo);
        msg.setSubject(subject);
        msg.setContent(message, "text/html");
        Transport.send(msg);
    } catch (MessagingException e) {
        System.out.println("SendMail:postMail - " + e.getMessage() + "; " + e.getCause());
    }
}


private class SMTPAuthenticator extends javax.mail.Authenticator {

    public PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication("username@gmail.com", "password");
    }
}

}

Everything worsk fine but when recipients recive the message, the sender is not the one I specified but the one I used for the authentication. So in this case, the sender is "username@gmail.com" instead of "me@gmail.com" that I used for the instruction message.setFrom.

一切都很好,但当收件人收到邮件时,发件人不是我指定的那个,而是我用于验证的那个。所以在这种情况下,发件人是“username@gmail.com”而不是我用于指令message.setFrom的“me@gmail.com”。

Does anyone know what is wrong?

有谁知道什么是错的?

1 个解决方案

#1


0  

you can try to add

你可以尝试添加

 props.put("mail.from", "me@gmail.com");

Which is used not in the message but at the beginning of the SMTP Transaction.

哪个不在消息中使用,而是在SMTP事务的开头使用。

See http://www.tcpipguide.com/free/t_SMTPMailTransactionProcess-3.htm

and http://javamail.kenai.com/nonav/javadocs/

#1


0  

you can try to add

你可以尝试添加

 props.put("mail.from", "me@gmail.com");

Which is used not in the message but at the beginning of the SMTP Transaction.

哪个不在消息中使用,而是在SMTP事务的开头使用。

See http://www.tcpipguide.com/free/t_SMTPMailTransactionProcess-3.htm

and http://javamail.kenai.com/nonav/javadocs/