Java mail, set reply-to address not working

user1133832 picture user1133832 · Jan 19, 2012 · Viewed 32k times · Source

I wrote a small email sending program in java, it has from, to and reply-to address, when the client tries to reply to the mail, it should be able to reply to the reply-to address. Currently it's not working, my code is below:

// File Name SendEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendEmail
{
   public static void main(String [] args)
   {

      // Recipient's email ID needs to be mentioned.
      String to = "[email protected]";

      // Sender's email ID needs to be mentioned
      String from = "[email protected]";

      // Assuming you are sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();
    properties.put("mail.smtp.from", "[email protected]");

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is the Subject Line!");

         // Now set the actual message
         message.setText("New Message goes here");

         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

I used real gmail accounts. Can anyone help..?

Answer

Joaquín I. Rbboles picture Joaquín I. Rbboles · Nov 16, 2012

Try:

MimeMessage message = new MimeMessage(session);
message.setReplyTo(new javax.mail.Address[]
{
    new javax.mail.internet.InternetAddress("[email protected]")
});