JavaMail 轉發電子郵件

在本章中,我們將看到如何使用JavaMail API來轉發電子郵件。接着在下面的程序的基本步驟是:

  • 獲取Session對象與POP和SMTP服務器的細節的屬性。我們需要的POP細節來檢索信息和SMPT詳細信息發送郵件。

  • 創建POP3存儲對象,並連接到存儲。

  • 創建文件夾對象,並在您的郵箱中打開相應的文件夾。

  • 檢索消息。

  • 遍歷的消息,如果你想轉發鍵入「Y」或「y」。

  • 得到消息的所有信息(收件人,發件人,主題,內容)。

  • 通過與組成消息的各個部分的工作建立轉發消息。第一部分將是消息的文本和第二部分將要轉發的郵件。結合兩成多部分。那麼你多部分添加到妥善處理消息併發送它。

  • 關閉傳輸,文件夾和存儲對象分別。

在這裏,我們使用JangoSMPT服務器通過該電子郵件被髮送到我們的目標電子郵件地址。設置是在環境設置章節解釋。

創建Java類

創建一個Java類文件ForwardEmail,是其內容如下:

package com.yiibai; 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. 我們需要javax.mail.jar 和 activation.jar 在 classpath中。執行下面的命令從命令提示符編譯類(兩個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 JavaMail