Search code examples
javamime-message

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. 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("[email protected]", "PASSWORD");
        }
      });
    try{
         MimeMessage message = new MimeMessage(session);
         try {
            message.setFrom(new InternetAddress("[email protected]", "FAKE NAME"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
         message.setReplyTo(new Address[]{new InternetAddress("[email protected]")});
         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 <[email protected]>

I want it to read:

from:    FAKE NAME <[email protected]>

What am I doing wrong? Any help is appreciated!


Solution

  • 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