简体   繁体   English

在Java MimeMessage中设置“ from”标头字段无法正常工作

[英]Setting the “from” header field in Java MimeMessage not working correctly

For a web application I'm working on I made a method to send email notifications. 对于正在使用的Web应用程序,我制定了一种发送电子邮件通知的方法。 The message has to come from a specific account, but I would like the "from" header field to read as an entirely different email address. 该邮件必须来自特定帐户,但我希望“发件人”标头字段作为完全不同的电子邮件地址读取。 Here is my code (I've changed the actual email addresses to fake ones): 这是我的代码(我已经将实际的电子邮件地址更改为伪造的电子邮件地址):

public static boolean sendEmail(List<String> recipients, String subject, String content){
    String header = "This is an automated message:<br />"+"<br />";
    String footer = "<br /><br />unsubscribe link here";
    content = header + content + footer;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            //This is where the email account name and password are set and can be changed
            return new PasswordAuthentication("ACTUAL.ADRESS@gmail.com", "PASSWORD");
        }
      });
    try{
         MimeMessage message = new MimeMessage(session);
         try {
            message.setFrom(new InternetAddress("FAKE.ADDRESS@gmail.com", "FAKE NAME"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
         message.setReplyTo(new Address[]{new InternetAddress("no-reply@gmail.com")});
         for(String recipient: recipients){
             message.addRecipient(Message.RecipientType.BCC,new InternetAddress(recipient));
         }
         message.setSubject(subject);
         message.setContent(content,"text/html");
         Transport.send(message);
         return true;
      }catch (MessagingException mex) {
         mex.printStackTrace();
         return false;
      }
}

For the above method sending an email with it will have the following email header: 对于上述方法,发送电子邮件将具有以下电子邮件标头:

from:    FAKE NAME <ACTUAL.ADRESS@gmail.com>

I want it to read: 我希望它读为:

from:    FAKE NAME <FAKE.ADRESS@gmail.com>

What am I doing wrong? 我究竟做错了什么? Any help is appreciated! 任何帮助表示赞赏!

What you are looking to do is called "spoofing." 您想要做的就是所谓的“欺骗”。 It appears as though you are using Google's SMTP servers, if this is the case, you will not be able to do this successfully. 似乎您正在使用Google的SMTP服务器,如果是这种情况,您将无法成功执行此操作。 For security purposes, Google will only allow the "from" address to be the authenticated email address. 为了安全起见,Google仅允许将“发件人”地址作为经过身份验证的电子邮件地址。

See this related question 看到这个相关的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM