package com.mail;
 
  import java.util.Properties;
 
  import javax.mail.*;
  import javax.mail.internet.*;
 
 public class ForwardMail {
 
 private static final String HOST_NAME = "pop.qq.com";
 private static final String SEND_HOST_NAME = "smtp.qq.com";
 private static final String PASSWORD = "********";
 private static final String EMAIL_FROM = "******@qq.com";
 private static final String USER_NAME = "*******@qq.com";
 private static final String PROTOCOL = "pop3";
 private static final String SEND_PROTOCOL = "smtp";
 
 public static void forwardMail(Session session, Message message) throws Exception {
 // 創建轉發郵件信息
 Message forward = new MimeMessage(session);
 // 設置主題
 forward.setSubject("Fwd: " + message.getSubject());
 forward.setFrom(new InternetAddress(EMAIL_FROM));
 forward.addRecipient(Message.RecipientType.TO, new InternetAddress("********@sina.com"));
 // 文字郵件體部分
 BodyPart messageBodyPart = new MimeBodyPart();
 messageBodyPart.setText( "郵件轉發" );
 //創建Multipart的容器
 Multipart multipart = new MimeMultipart();
 multipart.addBodyPart(messageBodyPart);
 // 被轉發的文字郵件體部分
 messageBodyPart = new MimeBodyPart();
 messageBodyPart.setDataHandler(message.getDataHandler());
 // 添加到Multipart容器
 multipart.addBodyPart(messageBodyPart);
 forward.setContent(multipart);
 // 發送
 Transport.send(forward); 
 System.out.println("msg forward ....");
 }
 
 public static void listMail() throws Exception {
 Properties props = new Properties();
 props.put("mail.smtp.host", SEND_HOST_NAME);
 props.put("mail.pop.host", HOST_NAME);
 props.put("mail.transport.protocol","smtp");
 props.put("mail.smtp.auth", "true");
 
 
 Session session = Session.getDefaultInstance(props, new SimpleAuthenticator(USER_NAME, PASSWORD)); 
 Store store = session.getStore(PROTOCOL); 
 store.connect(HOST_NAME, USER_NAME, PASSWORD);
 Folder folder = store.getFolder("INBOX");
 folder.open(Folder.READ_ONLY); 
 Message[] messages = folder.getMessages(); 
 InternetAddress address; 
 for (int i = messages.length-1; i >= 0; i--) { 
 address = (InternetAddress)messages[i].getFrom()[0]; 
 /*
 if(address != null) { 
 System.out.println(address.getPersonal()); 
 } 
 */
 if (null != address && "秋天的童話".equals(address.getPersonal())) { 
 System.out.println("第" + i + "個:" + messages[i].getSubject()); 
 //轉發郵件
 forwardMail(session, messages[i]);
 } 
 } 
 folder.close(true); 
 store.close();
 }
 
 public static void main(String[] args) {
 try {
 listMail();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 }

 本文轉自:http://www.cnblogs.com/qianru/archive/2010/11/04/1869132.html          

創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()