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

本秂侑毒 提交于 2019-12-02 08:49:19

问题


For a web application I'm working on I made a method to send email notifications. 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!


回答1:


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. For security purposes, Google will only allow the "from" address to be the authenticated email address.

See this related question



来源:https://stackoverflow.com/questions/23022600/setting-the-from-header-field-in-java-mimemessage-not-working-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!