javaMail 设置邮件回执
时间: 2023-07-04 17:24:06 浏览: 268
javamail 回执邮件资料
3星 · 编辑精心推荐
要设置邮件回执,可以使用 JavaMail API 中的 Receipt类,具体步骤如下:
1. 创建一个邮件会话对象,例如:
```java
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
```
2. 创建一个 MimeMessage 对象,设置发送人、收件人、主题、内容等信息。
3. 创建一个 Receipt 对象,设置邮件回执的收件人地址:
```java
Receipt receipt = new Receipt(new InternetAddress("receipt@example.com"));
```
4. 将 Receipt 对象添加到 MimeMessage 中:
```java
message.setHeader("Disposition-Notification-To", receipt.getNotificationTo());
```
5. 发送邮件即可,当收件人打开邮件时,会自动发送回执。
完整代码示例:
```java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class MailSender {
public static void main(String[] args) throws MessagingException {
String username = "your_username";
String password = "your_password";
String from = "from@example.com";
String to = "to@example.com";
String subject = "Test Email";
String content = "This is a test email.";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(content);
Receipt receipt = new Receipt(new InternetAddress("receipt@example.com"));
message.setHeader("Disposition-Notification-To", receipt.getNotificationTo());
Transport.send(message);
}
}
```
阅读全文