Question

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!

Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top