📅  最后修改于: 2020-11-14 10:05:42             🧑  作者: Mango
邮件可能会被退回有多种原因。在rfc1211上将深入讨论此问题。只有服务器才能确定特定邮箱或用户名的存在。当服务器检测到错误时,它将向原始消息的发送者返回一条指示失败原因的消息。
有许多Internet标准涉及传递状态通知,但是大量服务器不支持这些新标准,而是使用临时技术来返回此类失败消息。因此,将退回的邮件与导致问题的原始邮件相关联变得非常困难。
JavaMail包括对传递状态通知的解析的支持。有许多技术和试探法可以解决此问题。技术之一是可变信封返回路径。您可以按照以下示例在信封中设置返回路径。这是退回邮件发送到的地址。您可能需要将此地址设置为与From:标头不同的通用地址,以便可以处理远程退回。这是通过在JavaMail中设置mail.smtp.from属性来完成的。
创建一个Java类文件SendEmail ,其内容如下:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
public static void main(String[] args) throws Exception {
String smtpServer = "smtp.gmail.com";
int port = 587;
final String userid = "youraddress";//change accordingly
final String password = "*****";//change accordingly
String contentType = "text/html";
String subject = "test: bounce an email to a different address " +
"from the sender";
String from = "youraddress@gmail.com";
String to = "bouncer@fauxmail.com";//some invalid address
String bounceAddr = "toaddress@gmail.com";//change accordingly
String body = "Test: get message to bounce to a separate email address";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.port", "587");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.from", bounceAddr);
Session mailSession = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userid, password);
}
});
MimeMessage message = new MimeMessage(mailSession);
message.addFrom(InternetAddress.parse(from));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setContent(body, contentType);
Transport transport = mailSession.getTransport();
try {
System.out.println("Sending ....");
transport.connect(smtpServer, port, userid, password);
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
System.out.println("Sending done ...");
} catch (Exception e) {
System.err.println("Error Sending: ");
e.printStackTrace();
}
transport.close();
}// end function main()
}
在这里,我们可以看到属性mail.smtp.from设置为与from地址不同。
现在我们的课程已经准备好,让我们编译上面的课程。我将类SendEmail.java保存到目录: / home / manisha / JavaMailAPIExercise 。我们将在类路径中需要jars javax.mail.jar和activation.jar 。从命令提示符处执行以下命令来编译类(两个罐子都放在/ home / manisha /目录中):
javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail.java
现在已经编译了该类,请执行以下命令来运行:
java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendEmail
您应该在命令控制台上看到以下消息:
Sending ....
Sending done ...