JavaMail详解(七)——邮件转发 - 高飞网
82 人阅读

JavaMail详解(七)——邮件转发

2016-11-24 10:44:09

    本节我们看看如何用JavaMail API转发一个邮件。基本的步骤如下:

  1. 获取持有POP和SMTP详情属性的Session对象。我们将使用POP详情查询消息,使用SMPT详情发送消息
  2. 创建POP3的Store对象并连接到Store
  3. 创建Folder对象并打开邮件中的相应文件夹
  4. 查询消息
  5. 遍历消息,键入Y或y就转发该邮件
  6. 获取消息的所有信息(To、From、Subject、Content)
  7. 通过组成消息的各部分来组建新的消息,第一部分是发送消息的文本,第二部分是转发的内容。将这两部分组合到一个复合体(multipart)中,然后添加上合适的发送者并发送它。
  8. 关闭Transport、folder和store对象。


创建一个ForwardEmail类,如下:


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class ForwardEmail {

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("mail.store.protocol", "pop3");
        properties.put("mail.pop3s.host", "pop.163.com");
        properties.put("mail.pop3s.port", "995");
        properties.put("mail.pop3.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.163.com");
        properties.put("mail.smtp.port", "25");
        Session session = Session.getDefaultInstance(properties);
        Store store = null;
        Folder folder = null;
        try {
            // session.setDebug(true);
            // 获取Store对象并连接到指定的主机
            store = session.getStore("pop3s");
            store.connect("pop.163.com", "xxxxxx@163.com", "xxxxxx");

            // 创建Folder对象并打开
            folder = store.getFolder("inbox");
            folder.open(Folder.READ_ONLY);
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            Message[] messages = folder.getMessages();
            if (messages.length != 0) {

                for (int i = 0, n = messages.length; i < n; i++) {
                    Message message = messages[i];
                    // 从消息中获取所有的信息
                    String from = InternetAddress.toString(message.getFrom());
                    if (from != null) {
                        System.out.println("From: " + from);
                    }
                    String replyTo = InternetAddress.toString(message.getReplyTo());
                    if (replyTo != null) {
                        System.out.println("Reply-to: " + replyTo);
                    }
                    String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
                    if (to != null) {
                        System.out.println("To: " + to);
                    }

                    String subject = message.getSubject();
                    if (subject != null) {
                        System.out.println("Subject: " + subject);
                    }
                    Date sent = message.getSentDate();
                    if (sent != null) {
                        System.out.println("Sent: " + sent);
                    }
                    System.out.print("Do you want to reply [y/n] : ");
                    String ans = reader.readLine();
                    if ("Y".equals(ans) || "y".equals(ans)) {
                        Message forward = new MimeMessage(session);
                        // 填充消息头
                        forward.setRecipients(Message.RecipientType.TO, InternetAddress.parse(from));
                        forward.setSubject("Fwd: " + message.getSubject());
                        forward.setFrom(new InternetAddress(to));

                        // 创建复合体
                        Multipart multipart = new MimeMultipart();
                        
                        MimeBodyPart textBodyPart = new MimeBodyPart();
                        textBodyPart.setText("转发.");
                        multipart.addBodyPart(textBodyPart);
                        // 创建复合消息体
                        MimeBodyPart messageBodyPart = new MimeBodyPart();
                        // 设置转发内容(原始消息)
                        messageBodyPart.setContent(message, "message/rfc822");// 该消息格式为封装格式
                        // 添加到复合体中
                        multipart.addBodyPart(messageBodyPart);
                        
                        // 关联复合消息
                        forward.setContent(multipart);
                        forward.saveChanges();

                        // 通过验证SMTP服务发送消息
                        // 创建一个Transport实例并调用发送消息方法
                        Transport t = session.getTransport("smtp");
                        try {
                            // 使用transport实例连接到smpt服务
                            t.connect("xxxxxx@163.com", "xxxxxx");
                            t.sendMessage(forward, forward.getAllRecipients());
                        } finally {
                            t.close();
                        }

                        System.out.println("message forwarded successfully....");
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (folder != null && store != null) {
                // 关闭sotre和folder对象
                try {
                    folder.close(false);
                    store.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}


转发邮件如下:


还没有评论!
54.205.153.192