如何使用 JavaMail 将返回路径设置为发件人地址以外的电子邮件地址?
3 回答
下面的代码做你想做的事,并以正确的方式做。重新阅读您自己在评论中发布的内容
当投递 SMTP 服务器对邮件进行“最终投递”时,它会在邮件数据的开头插入一个返回路径行。需要使用返回路径;邮件系统必须支持它。return-path 行保留了来自 MAIL 命令的信息。在这里,最终传递意味着邮件已离开 SMTP 环境。通常,这意味着它已交付给目标用户或相关的邮件投递,但在某些情况下,它可能会被另一个邮件系统进一步处理和传输。
几行之后。
消息发起 SMTP 系统不应发送已包含 Return-path 标头的消息。
如果您仔细阅读此内容,您将了解只有最终的 smtp-server/delivery 代理应该添加Return-Path
标头。这不是您作为客户(尝试发送邮件)应该做的事情。最终的 smtp-server 将基于Return-Path
信封(SMTP MAIL FROM
部分)的发件人地址的标头。
所以设置mail.smtp.from
是告诉java信封发件人地址应该与from
部分不同的正确方法。
如果您在理解不同from
之处有困难,请查看 telnet smtp-session。应该replyto@example.com
对应smtp.mail.from
到哪里from@example.com
m.addFrom(...);
telnet smtp.example.com 25
220 smtp.example.com ESMTP .....
helo computername
250 smtp.example.com Hello computername [123.123.123.123]
mail from:<replyto@example.com>
250 <replyto@example.com> is syntactically correct
rcpt to:<rcpt@foo.com>
250 <rcpt@foo.com> verified
data
354 Enter message, ending with "." on a line by itself
To: Joey <to@joey.com>
From: Joey <from@example.com>
Subject: Joey
Hey Joey!
.
250 OK id=....
Quit
props.put("mail.smtp.from", "replyto@example.com");
Session session = Session.getDefaultInstance(props, null);
MimeMessage m = new MimeMessage(session);
m.addFrom(InternetAddress.parse("from@example.com"));
我遇到了同样的问题,发现唯一的解决方案是讨论放置属性 "mail.smtp.from" props.put("mail.smtp.from", "replyto@example.com");
这个解决方案仍然不适合我,因为我要发送来自不同用户的大量电子邮件,因此为每封电子邮件重新创建会话对于生产力来说是可怕的。
所以我在阅读 JavaMail 源码后找到了另一个解决方案:
1) 使用 SMTPMessage(extends MimeMessage) 而不是 MimeMessage。
2) 使用 setEnvelopeFrom(String) 方法。
3)使用 SMTPTransport 发送电子邮件(我没有尝试与其他人)。
这是一个代码示例:
SMTPMessage message = new SMTPMessage(session);
message.setEnvelopeFrom("returnpath@hotmail.com");
...
transport.sendMessage(message, message.getAllRecipients());
I found that if the 'mail.protocol' property is set to something other than 'smtp' (like 'smtps'), then only the following would work:
props.put("mail.smtps.from", "replyto@example.com");
This allowed me to avoid using the SMTPMessage class as described in GiorgosDev's answer (classes in the 'com.sun' package aren't intended to be public API).