我正在尝试通过Java Mail应用程序将邮件发送给我的朋友。我能够成功完成此操作,但是邮箱中的收件人列显示了完整的电子邮件地址,而不是发送者的姓名。我尝试更改各种参数,但是邮箱仍然会显示完整的电子邮件地址,而不是发件人的姓名。
使用此方法发送消息:
public void send(String key){ String to=key; String from="mygmailid"; String subject="wassp"; String text="Hello"; Properties props=new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.user", "myname"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); Session mailSession=Session.getDefaultInstance(props); Message simpleMessage=new MimeMessage(mailSession); InternetAddress fromAddress=null; InternetAddress toAddress=null; try{ fromAddress=new InternetAddress(from); toAddress=new InternetAddress(to); } catch(AddressException e){ e.printStackTrace(); } try{ simpleMessage.setFrom(fromAddress); simpleMessage.setRecipient(RecipientType.TO,toAddress); simpleMessage.setSubject(subject); simpleMessage.setText(text); transport.connect("smtp.gmail.com",465, "myid@gmail.com", "mygmailpassword"); transport.sendMessage(simpleMessage, simpleMessage.getAllRecipients()); transport.close(); } catch(MessagingException e){ e.printStackTrace(); } }
我将此方法称为:
public static void main(String[] args) { MailSender mailer=new MailSender(); mailer.send("friendmail@gmail.com"); }
您可以在InternetAddress使用中设置名称
InternetAddress
new InternetAddress("mail@example.com", "Your Name");