I'm trying to get Java mail to send bounced email to a different address than the sender's address and not send the bounce message to the sender at all.
So far I can't do either in a test program ( below ).
The sender is "[email protected]". I want bounce messages to go and only go to "[email protected]"
I'm trying setting both the reply-to address and the Return-Path: header, but the bounces do not go to [email protected], only to [email protected]
When looking at the header of the bounce message the Return-Path: header is getting set to the sender, [email protected], not to [email protected] the way I want it to be.
I'm using javamail 1.4
Thanks in advance for any help or tips
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import java.util.Properties;
public class SendEmail {
public static void main(String[] args) throws Exception{
String smtpServer = "msg.abc.acme.cp,";
int port = 25;
String userid = "authorized.person";
String password = "password";
String contentType = "text/html";
String subject = "test: bounce an email to a different address from the sender";
String from = "[email protected]";
String to = "[email protected]";
String replyto = "[email protected]";
String body = "Test: get message to bounce to a separate email address";
InternetAddress[] arrayReplyTo = new InternetAddress[1];
arrayReplyTo[0] = new InternetAddress(replyto);
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", smtpServer);
Session mailSession = Session.getInstance(props);
// Get runtime more runtime output when attempting to send an email
//mailSession.setDebug(true);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.setReplyTo(arrayReplyTo);
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setContent(body,contentType);
message.setHeader("Return-Path:","<[email protected]>");
Transport transport = mailSession.getTransport();
try{
System.out.println("Sending ....");
transport.connect(smtpServer, port, userid, password);
transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
System.out.println("Sending done ...");
}
catch(Exception e) {
System.err.println("Error Sending: ");
e.printStackTrace();
}
transport.close();
}// end function main()
}// end class SendEmail
You need to set the "envelope from" address. See the javadocs for the com.sun.mail.smtp package for the property you can use to set it, or use the SMTPMessage class to set it.
And then hope that the mail server bouncing the message does the right thing and follows the spec...