JavaMail - 转发电子邮件

  • 简述

    在本章中,我们将看到如何使用 JavaMail API 转发电子邮件。以下程序中遵循的基本步骤是:
    • 在属性中获取带有 POP 和 SMPT 服务器详细信息的 Session 对象。我们需要 POP 详细信息来检索消息和 SMPT 详细信息来发送消息。
    • 创建 POP3 商店对象并连接到商店。
    • 创建 Folder 对象并在您的邮箱中打开相应的文件夹。
    • 检索消息。
    • 如果要转发,则遍历消息并键入“Y”或“y”。
    • 获取邮件的所有信息(收件人、发件人、主题、内容)。
    • 通过处理组成消息的部分来构建转发消息。第一部分是消息的文本,第二部分是要转发的消息。将两者合并为一个多部分。然后将多部分添加到正确寻址的消息中并发送。
    • 分别关闭传输、文件夹和存储对象。
    在这里,我们使用了 JangoSMPT 服务器,通过该服务器将电子邮件发送到我们的目标电子邮件地址。环境设置章节中解释了。
  • 创建 Java 类

    创建一个java类文件 ForwardEmail,其内容如下:
    
    package com.jc2182;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.BodyPart;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.Multipart;
    import javax.mail.PasswordAuthentication;
    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.gmail.com");
          properties.put("mail.pop3s.port", "995");
          properties.put("mail.pop3.starttls.enable", "true");
          properties.put("mail.smtp.auth", "true");
          properties.put("mail.smtp.host", "relay.jangosmtp.net");
          properties.put("mail.smtp.port", "25");
          Session session = Session.getDefaultInstance(properties);
          try {
             // session.setDebug(true);
             // Get a Store object and connect to the current host
             Store store = session.getStore("pop3s");
             store.connect("pop.gmail.com", "xyz@gmail.com",
                "*****");//change the user and password accordingly
             // Create a Folder object and open the folder
             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];
                // Get all the information from the message
                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);
                   // Fill in header
                   forward.setRecipients(Message.RecipientType.TO,
                   InternetAddress.parse(from));
                   forward.setSubject("Fwd: " + message.getSubject());
                   forward.setFrom(new InternetAddress(to));
                   // Create the message part
                   MimeBodyPart messageBodyPart = new MimeBodyPart();
                   // Create a multipart message
                   Multipart multipart = new MimeMultipart();
                   // set content
                   messageBodyPart.setContent(message, "message/rfc822");
                   // Add part to multi part
                   multipart.addBodyPart(messageBodyPart);
                   // Associate multi-part with message
                   forward.setContent(multipart);
                   forward.saveChanges();
                   // Send the message by authenticating the SMTP server
                   // Create a Transport instance and call the sendMessage
                   Transport t = session.getTransport("smtp");
                   try {
                      //connect to the smpt server using transport instance
            //change the user and password accordingly
                      t.connect("abc", "*****");
                      t.sendMessage(forward, forward.getAllRecipients());
                   } finally {
                      t.close();
                   }
                   System.out.println("message forwarded successfully....");
                // close the store and folder objects
                folder.close(false);
                store.close();
                }// end if
             }// end for
       }// end if
       } catch (Exception e) {
          e.printStackTrace();
       }
    }
    }
    
    您可以通过取消注释session.setDebug(true);语句来设置调试
  • 编译运行

    现在我们的类已经准备好了,让我们编译上面的类。我已将类 ForwardEmail.java 保存到目录:/home/manisha/JavaMailAPIExercise. 我们需要类路径中的 jars javax.mail.jaractivation.jar。从命令提示符执行以下命令以编译类(两个 jar 文件都放在 /home/manisha/ 目录中):
    
    javac -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: ForwardEmail.java
    
    现在类已经编译完成,执行以下命令运行:
    
    java -cp /home/manisha/activation.jar:/home/manisha/javax.mail.jar: ForwardEmail
    
  • 验证输出

    您应该在命令控制台上看到以下消息:
    
    From: ABC <abc@gmail.com>
    Reply-to: abc@trioteksolutions.com
    To: XYZ <xyz@gmail.com>
    Subject: Hi today is a nice day
    Sent: Thu Oct 17 15:58:37 IST 2013
    Do you want to reply [y/n] : y
    message forwarded successfully....
    
    检查邮件发送到的收件箱。在我们的例子中,转发的消息如下所示:
    JavaMail API 转发电子邮件 JavaMail API 转发电子邮件