如何在收件箱中设置发件人名称而不是发件人名称与java中的其他名称

时间:2017-09-02 11:20:55

标签: java email

我正在使用java邮件API发送邮件。我希望发件人姓名发件人姓名是我的示例中的其他名称发件人邮件地址是from@example.com但我希望它在收件箱中是其他名称 这是我的例子

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

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

  String host="smtp.gmail.com";  
  final String from="from@example.com";//change accordingly  
  final String password="12345";//change accordingly  

  String to="to@example.com";//change accordingly  

   //Get the session object  
   Properties props = new Properties();       
   props.put("mail.smtp.auth", "true"); 
   props.put("mail.smtp.starttls.enable", "true"); 
   props.put("mail.smtp.host", host);
   props.put("mail.smtp.port", "587"); 

   Session session = Session.getDefaultInstance(props,  
    new javax.mail.Authenticator() {  
      protected PasswordAuthentication getPasswordAuthentication() {  
    return new PasswordAuthentication(from,password);   
      }  
    });  

   //Compose the message  
    try {   
     MimeMessage message = new MimeMessage(session);  
     message.setFrom(new InternetAddress(from));  
     message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
     message.setSubject("Test");  
     message.setText("hello");
    //send the message  
     Transport.send(message);  

     System.out.println("message sent successfully...");  

     } catch (MessagingException e) {e.printStackTrace();}  
 }  
}  

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

InternetAddress可以像这样使用:InternetAddress(mail, alias),意思是你要改变

message.setFrom(new InternetAddress(from));

message.setFrom(new InternetAddress(from, "Your Name"));

现在,收件人将from@example.com视为发件人姓名,而不是Your Name