Java邮件,设置回复地址不起作用

时间:2012-01-19 12:47:06

标签: java javamail

我在java中编写了一个小型电子邮件发送程序,它有fromtoreply-to地址,当客户端尝试回复邮件时,它应该能够回复到reply-to地址。 目前它无法正常工作,我的代码如下:

// 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 = "xyz@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "abcd@gmail.com";

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

      // Get system properties
      Properties properties = System.getProperties();
    properties.put("mail.smtp.from", "mnop@gmail.com");

      // 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();
      }
   }
}

我使用了真正的Gmail帐户。谁能帮忙..?

2 个答案:

答案 0 :(得分:31)

尝试:

MimeMessage message = new MimeMessage(session);
message.setReplyTo(new javax.mail.Address[]
{
    new javax.mail.internet.InternetAddress("mnop@gmail.com")
});

答案 1 :(得分:26)

Message.setReplyTo()

请注意:

  • “from”与“回复”
  • 不同
  • 根据spec,from-address的属性为“mail.from”
  • getDefaultInstance的文档指定,如果没有现有的默认实例,则仅创建新实例,并且仅在创建新实例时使用这些属性。此外,默认实例是全局值并将被重复使用,因此除非您想在所有电子邮件中使用相同的“from”-address,否则您需要创建新会话(使用getInstance())