【问题标题】:How to specify Display Name in Gmail SMTP?如何在 Gmail SMTP 中指定显示名称?
【发布时间】:2019-12-28 11:52:02
【问题描述】:

一个例子可以更好地解释我的问题:

如果“Mark Jones”拥有 xyz@gmail.com 并通过传统方法(Compose)向某人发送邮件,则收件人会收到一封标题为“Mark Jones”的邮件,后面跟着主题。但是通过 Gmail SMTP 发送的相同邮件的标题为“xyz”,后跟主题。

我正在为 SMTP 使用 javax.mail 库。即使我通过 Java SMTP 发送,我也希望显示“Mark Jones”而不是“xyz”。有什么方法可以实现吗?
以下是我目前使用的代码:

    System.setProperty("java.net.preferIPv4Stack" , "true");
    Properties props = new Properties();
    props.put("mail.smtps.user", "xyz@gmail.com");
    props.put("mail.smtps.host", "smtp.gmail.com");
    props.put("mail.smtps.port", "465");
    props.put("mail.smtps.starttls.enable", "true");
    props.put("mail.smtps.debug", "true");
    props.put("mail.smtps.auth", "true");

    Session session = Session.getInstance(props,
            new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("xyz@gmail.com", "password");
        }
    });
    MimeMessage msg = new MimeMessage(session);
    try {
        msg.setSubject(this.subject);
        msg.setFrom(new InternetAddress("xyz@gmail.com"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(this.to));
        msg.setText(this.body);
        try (Transport transport = session.getTransport("smtps")) {
            transport.connect("smtp.gmail.com", Integer.valueOf("465"), "Mark Jones", "password");
            transport.sendMessage(msg, msg.getAllRecipients());
        }
    } catch (AddressException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }

【问题讨论】:

标签: java jakarta-mail


【解决方案1】:

正如Bill Shannon 建议的那样,下面的代码可以解决问题

try{ 
    msg.setFrom(new InternetAddress("xyz@gmail.com","Mark Jones")); 
}catch(UnsupportedEncodingException e){
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 2018-03-31
    • 2021-05-26
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 2017-07-13
    • 2013-03-31
    相关资源
    最近更新 更多