`
tianyalinfeng
  • 浏览: 433486 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

JavaMail收发邮件

    博客分类:
  • Java
 
阅读更多

mail-1.4.4.jar

 

package mail;

import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
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 MailSender {
 /**
  * 以文本格式发送邮件
  *
  * @param mailInfo
  *            待发送的邮件的信息
  */
 public boolean sendTextMail(MailInfo mailInfo) {
  // 判断是否需要身份认证
  MailAuthenticator authenticator = null;
  Properties pro = mailInfo.getProperties();
  if (mailInfo.isValidate()) {
   // 如果需要身份认证,则创建一个密码验证器
   authenticator = new MailAuthenticator(mailInfo.getUserName(),
     mailInfo.getPassword());
  }
  // 根据邮件会话属性和密码验证器构造一个发送邮件的session
  Session sendMailSession = Session
    .getDefaultInstance(pro, authenticator);
  try {
   // 根据session创建一个邮件消息
   Message mailMessage = new MimeMessage(sendMailSession);
   // 创建邮件发送者地址
   Address from = new InternetAddress(mailInfo.getFromAddress());
   // 设置邮件消息的发送者
   mailMessage.setFrom(from);
   // 创建邮件的接收者地址,并设置到邮件消息中
   Address to = new InternetAddress(mailInfo.getToAddress());
   mailMessage.setRecipient(Message.RecipientType.TO, to);
   // 设置邮件消息的主题
   mailMessage.setSubject(mailInfo.getSubject());
   // 设置邮件消息发送的时间
   mailMessage.setSentDate(new Date());
   // 设置邮件消息的主要内容
   String mailContent = mailInfo.getContent();
   mailMessage.setText(mailContent);
   // 发送邮件
   Transport.send(mailMessage);
   return true;
  } catch (MessagingException ex) {
   ex.printStackTrace();
  }
  return false;
 }

 /**
  * 以HTML格式发送邮件
  *
  * @param mailInfo
  *            待发送的邮件信息
  */
 public boolean sendHtmlMail(MailInfo mailInfo) {
  // 判断是否需要身份认证
  MailAuthenticator authenticator = null;
  Properties pro = mailInfo.getProperties();
  // 如果需要身份认证,则创建一个密码验证器
  if (mailInfo.isValidate()) {
   authenticator = new MailAuthenticator(mailInfo.getUserName(),
     mailInfo.getPassword());
  }
  // 根据邮件会话属性和密码验证器构造一个发送邮件的session
  Session sendMailSession = Session
    .getDefaultInstance(pro, authenticator);
  try {
   // 根据session创建一个邮件消息
   Message mailMessage = new MimeMessage(sendMailSession);
   // 创建邮件发送者地址
   Address from = new InternetAddress(mailInfo.getFromAddress());
   // 设置邮件消息的发送者
   mailMessage.setFrom(from);
   // 创建邮件的接收者地址,并设置到邮件消息中
   Address to = new InternetAddress(mailInfo.getToAddress());
   // Message.RecipientType.TO属性表示接收者的类型为TO
   mailMessage.setRecipient(Message.RecipientType.TO, to);
   // 设置邮件消息的主题
   mailMessage.setSubject(mailInfo.getSubject());
   // 设置邮件消息发送的时间
   mailMessage.setSentDate(new Date());
   // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
   Multipart mainPart = new MimeMultipart();
   // 创建一个包含HTML内容的MimeBodyPart
   BodyPart html = new MimeBodyPart();
   // 设置HTML内容
   html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
   mainPart.addBodyPart(html);
   // 将MiniMultipart对象设置为邮件内容
   mailMessage.setContent(mainPart);
   // 发送邮件
   Transport.send(mailMessage);
   return true;
  } catch (MessagingException ex) {
   ex.printStackTrace();
  }
  return false;
 }

 public static void main(String[] args) {
  // 这个类主要是设置邮件
  MailInfo mailInfo = new MailInfo();
  mailInfo.setMailServerHost("smtp.qq.com");
  mailInfo.setMailServerPort("25");
  mailInfo.setValidate(true);
  mailInfo.setUserName("123456@qq.com");
  mailInfo.setPassword("123456");// 您的邮箱密码
  mailInfo.setFromAddress("123456@qq.com");
  mailInfo.setToAddress("123456@qq.com");
  mailInfo.setSubject("测试邮件");
  mailInfo.setContent("测试邮件的内容");
  // 这个类主要来发送邮件
  MailSender sms = new MailSender();
  sms.sendTextMail(mailInfo);// 发送文体格式
  // sms.sendHtmlMail(mailInfo);// 发送html格式
 }
}

 

 

package mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MailAuthenticator extends Authenticator {
 String userName = null;
 String password = null;

 public MailAuthenticator() {
 }

 public MailAuthenticator(String username, String password) {
  this.userName = username;
  this.password = password;
 }

 protected PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication(userName, password);
 }
}

 

package mail;

/**
 * 发送邮件需要使用的基本信息
 */
import java.util.Properties;

public class MailInfo {
 // 发送邮件的服务器的IP和端口
 private String mailServerHost;
 private String mailServerPort = "25";
 // 邮件发送者的地址
 private String fromAddress;
 // 邮件接收者的地址
 private String toAddress;
 // 登陆邮件发送服务器的用户名和密码
 private String userName;
 private String password;
 // 是否需要身份验证
 private boolean validate = false;
 // 邮件主题
 private String subject;
 // 邮件的文本内容
 private String content;
 // 邮件附件的文件名
 private String[] attachFileNames;

 /**
  * 获得邮件会话属性
  */
 public Properties getProperties() {
  Properties p = new Properties();
  p.put("mail.smtp.host", this.mailServerHost);
  p.put("mail.smtp.port", this.mailServerPort);
  p.put("mail.smtp.auth", validate ? "true" : "false");
  return p;
 }

 public String getMailServerHost() {
  return mailServerHost;
 }

 public void setMailServerHost(String mailServerHost) {
  this.mailServerHost = mailServerHost;
 }

 public String getMailServerPort() {
  return mailServerPort;
 }

 public void setMailServerPort(String mailServerPort) {
  this.mailServerPort = mailServerPort;
 }

 public boolean isValidate() {
  return validate;
 }

 public void setValidate(boolean validate) {
  this.validate = validate;
 }

 public String[] getAttachFileNames() {
  return attachFileNames;
 }

 public void setAttachFileNames(String[] fileNames) {
  this.attachFileNames = fileNames;
 }

 public String getFromAddress() {
  return fromAddress;
 }

 public void setFromAddress(String fromAddress) {
  this.fromAddress = fromAddress;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getToAddress() {
  return toAddress;
 }

 public void setToAddress(String toAddress) {
  this.toAddress = toAddress;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getSubject() {
  return subject;
 }

 public void setSubject(String subject) {
  this.subject = subject;
 }

 public String getContent() {
  return content;
 }

 public void setContent(String textContent) {
  this.content = textContent;
 }
}

 

package mail;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class MailReciver {
 private MimeMessage msg = null;
 private String saveAttachPath = "";
 private StringBuffer bodytext = new StringBuffer();
 private String dateformate = "yy-MM-dd HH:mm";

 public MailReciver(MimeMessage msg) {
  this.msg = msg;
 }

 public void setMsg(MimeMessage msg) {
  this.msg = msg;
 }

 /** * 获取发送邮件者信息 * @return * @throws MessagingException */
 public String getFrom() throws MessagingException {
  InternetAddress[] address = (InternetAddress[]) msg.getFrom();
  String from = address[0].getAddress();
  if (from == null) {
   from = "";
  }
  String personal = address[0].getPersonal();
  if (personal == null) {
   personal = "";
  }
  String fromaddr = personal + "<" + from + ">";
  return fromaddr;
 }

 /**
  * * 获取邮件收件人,抄送,密送的地址和信息。根据所传递的参数不同 "to"-->收件人,"cc"-->抄送人地址,"bcc"-->密送地址 * @param
  * type * @return * @throws MessagingException * @throws
  * UnsupportedEncodingException
  */
 public String getMailAddress(String type) throws MessagingException,
   UnsupportedEncodingException {
  String mailaddr = "";
  String addrType = type.toUpperCase();
  InternetAddress[] address = null;
  if (addrType.equals("TO") || addrType.equals("CC")
    || addrType.equals("BCC")) {
   if (addrType.equals("TO")) {
    address = (InternetAddress[]) msg
      .getRecipients(Message.RecipientType.TO);
   }
   if (addrType.equals("CC")) {
    address = (InternetAddress[]) msg
      .getRecipients(Message.RecipientType.CC);
   }
   if (addrType.equals("BCC")) {
    address = (InternetAddress[]) msg
      .getRecipients(Message.RecipientType.BCC);
   }
   if (address != null) {
    for (int i = 0; i < address.length; i++) {
     String mail = address[i].getAddress();
     if (mail == null) {
      mail = "";
     } else {
      mail = MimeUtility.decodeText(mail);
     }
     String personal = address[i].getPersonal();
     if (personal == null) {
      personal = "";
     } else {
      personal = MimeUtility.decodeText(personal);
     }
     String compositeto = personal + "<" + mail + ">";
     mailaddr += "," + compositeto;
    }
    mailaddr = mailaddr.substring(1);
   }
  } else {
   throw new RuntimeException("Error email Type!");
  }
  return mailaddr;
 }

 /**
  * * 获取邮件主题 * @return * @throws UnsupportedEncodingException * @throws
  * MessagingException
  */
 public String getSubject() throws UnsupportedEncodingException,
   MessagingException {
  String subject = "";
  subject = MimeUtility.decodeText(msg.getSubject());
  if (subject == null) {
   subject = "";
  }
  return subject;
 }

 /** * 获取邮件发送日期 * @return * @throws MessagingException */
 public String getSendDate() throws MessagingException {
  Date sendDate = msg.getSentDate();
  SimpleDateFormat smd = new SimpleDateFormat(dateformate);
  return smd.format(sendDate);
 }

 /** * 获取邮件正文内容 * @return */
 public String getBodyText() {
  return bodytext.toString();
 }

 /**
  * * 解析邮件,将得到的邮件内容保存到一个stringBuffer对象中,解析邮件 主要根据MimeType的不同执行不同的操作,一步一步的解析 * @param
  * part * @throws MessagingException * @throws IOException
  */
 public void getMailContent(Part part) throws MessagingException,
   IOException {
  String contentType = part.getContentType();
  int nameindex = contentType.indexOf("name");
  boolean conname = false;
  if (nameindex != -1) {
   conname = true;
  }
  System.out.println("CONTENTTYPE:" + contentType);
  if (part.isMimeType("text/plain") && !conname) {
   bodytext.append((String) part.getContent());
  } else if (part.isMimeType("text/html") && !conname) {
   bodytext.append((String) part.getContent());
  } else if (part.isMimeType("multipart/*")) {
   Multipart multipart = (Multipart) part.getContent();
   int count = multipart.getCount();
   for (int i = 0; i < count; i++) {
    getMailContent(multipart.getBodyPart(i));
   }
  } else if (part.isMimeType("message/rfc822")) {
   getMailContent((Part) part.getContent());
  }
 }

 /**
  * * 判断邮件是否需要回执,如需回执返回true,否则返回false * @return
  *
  * @throws MessagingException
  */
 public boolean getReplySign() throws MessagingException {
  boolean replySign = false;
  String needreply[] = msg.getHeader("Disposition-Notification-TO");
  if (needreply != null) {
   replySign = true;
  }
  return replySign;
 }

 /** * 获取此邮件的message-id * @return * @throws MessagingException */
 public String getMessageId() throws MessagingException {
  return msg.getMessageID();
 }

 /** * 判断此邮件是否已读,如果未读则返回true,已读返回false * @return * @throws MessagingException */
 public boolean isNew() throws MessagingException {
  boolean isnew = true;
  Flags flags = ((Message) msg).getFlags();
  Flags.Flag[] flag = flags.getSystemFlags();
  System.out.println("flags's length:" + flag.length);
  for (int i = 0; i < flag.length; i++) {
   if (flag[i] == Flags.Flag.SEEN) {
    isnew = false;
    System.out.println("seen message .......");
    break;
   }
  }
  return isnew;
 }

 /**
  * 由于pop协议中无法用isNew方法来判断是否已读,所以用如下方式实现
  *
  * @return
  * @throws MessagingException
  */
 public boolean isSeen() {
  File file = null;
  try {
   String id = getMessageId();
   String filePath = "c:/temp/" + URLEncoder.encode(id, "UTF-8")
     + ".txt";
   file = new File(filePath);
  } catch (Exception e) {
  }
  return existFile(file);
 }

 /**
  * * 判断是是否包含附件 * @param part * @return * @throws MessagingException * @throws
  * IOException
  */
 public boolean isContainAttch(Part part) throws MessagingException,
   IOException {
  boolean flag = false;
  if (part.isMimeType("multipart/*")) {
   Multipart multipart = (Multipart) part.getContent();
   int count = multipart.getCount();
   for (int i = 0; i < count; i++) {
    BodyPart bodypart = multipart.getBodyPart(i);
    String dispostion = bodypart.getDisposition();
    if ((dispostion != null)
      && (dispostion.equals(Part.ATTACHMENT) || dispostion
        .equals(Part.INLINE))) {
     flag = true;
    } else if (bodypart.isMimeType("multipart/*")) {
     flag = isContainAttch(bodypart);
    } else {
     String conType = bodypart.getContentType();
     if (conType.toLowerCase().indexOf("appliaction") != -1) {
      flag = true;
     }
     if (conType.toLowerCase().indexOf("name") != -1) {
      flag = true;
     }
    }
   }
  } else if (part.isMimeType("message/rfc822")) {
   flag = isContainAttch((Part) part.getContent());
  }
  return flag;
 }

 /** * 保存附件 * @param part * @throws MessagingException * @throws IOException */
 public void saveAttachMent(Part part) throws MessagingException,
   IOException {
  String filename = "";
  if (part.isMimeType("multipart/*")) {
   Multipart mp = (Multipart) part.getContent();
   for (int i = 0; i < mp.getCount(); i++) {
    BodyPart mpart = mp.getBodyPart(i);
    String dispostion = mpart.getDisposition();
    if ((dispostion != null)
      && (dispostion.equals(Part.ATTACHMENT) || dispostion
        .equals(Part.INLINE))) {
     filename = mpart.getFileName();
     if (filename.toLowerCase().indexOf("gb2312") != -1) {
      filename = MimeUtility.decodeText(filename);
     }
     saveFile(filename, mpart.getInputStream());
    } else if (mpart.isMimeType("multipart/*")) {
     saveAttachMent(mpart);
    } else {
     filename = mpart.getFileName();
     if (filename != null
       && (filename.toLowerCase().indexOf("gb2312") != -1)) {
      filename = MimeUtility.decodeText(filename);
     }
     saveFile(filename, mpart.getInputStream());
    }
   }
  } else if (part.isMimeType("message/rfc822")) {
   saveAttachMent((Part) part.getContent());
  }
 }

 /** * 获得保存附件的地址 * @return */
 public String getSaveAttchPath() {
  return saveAttachPath;
 }

 /** * 设置保存附件地址 * @param saveAttchPath */
 public void setSaveAttchPath(String saveAttchPath) {
  this.saveAttachPath = saveAttchPath;
 }

 /** * 设置日期格式 * @param dateformate */
 public void setDateformate(String dateformate) {
  this.dateformate = dateformate;
 }

 /** * 保存文件内容 * @param filename * @param inputStream * @throws IOException */
 private void saveFile(String filename, InputStream inputStream)
   throws IOException {
  String osname = System.getProperty("os.name");
  String storedir = getSaveAttchPath();
  String sepatror = "";
  if (osname == null) {
   osname = "";
  }
  if (osname.toLowerCase().indexOf("win") != -1) {
   sepatror = "//";
   if (storedir == null || "".equals(storedir)) {
    storedir = "d://temp";
   }
  } else {
   sepatror = "/";
   storedir = "/temp";
  }
  File storefile = new File(storedir + sepatror + filename);
  System.out.println("storefile's path:" + storefile.toString());
  BufferedOutputStream bos = null;
  BufferedInputStream bis = null;
  try {
   bos = new BufferedOutputStream(new FileOutputStream(storefile));
   bis = new BufferedInputStream(inputStream);
   int c;
   while ((c = bis.read()) != -1) {
    bos.write(c);
    bos.flush();
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   bos.close();
   bis.close();
  }
 }

 public void recive(Part part, int i) throws MessagingException, IOException {
  System.out.println("------------------START-----------------------");
  System.out.println("Message" + i + " subject:" + getSubject());
  System.out.println("Message" + i + " from:" + getFrom());
  System.out.println("Message" + i + " isNew:" + isNew());
  boolean flag = isContainAttch(part);
  System.out.println("Message" + i + " isContainAttch:" + flag);
  System.out.println("Message" + i + " replySign:" + getReplySign());
  getMailContent(part);
  System.out.println("Message" + i + " content:" + getBodyText());
  setSaveAttchPath("c://temp//" + i);
  if (flag) {
   // saveAttchMent(part);
  }
  // save id
  saveMsgId();
  System.out.println("------------------END-----------------------");
 }

 /**
  * 将已读邮件标记到硬盘
  */
 private void saveMsgId() {
  try {
   String id = getMessageId();
   writeToFile("c:/temp", id);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  *
  * 写文件
  *
  * @param dir
  * @param id
  * @throws UnsupportedEncodingException
  */
 private void writeToFile(String dir, String id) throws Exception {
  File path = new File(dir);
  if (!path.exists()) {
   path.mkdirs();
  }
  File f = new File(dir + "/" + URLEncoder.encode(id, "UTF-8") + ".txt");
  try {
   FileOutputStream fs = new FileOutputStream(f, false);
   OutputStreamWriter write = new OutputStreamWriter(fs, "UTF-8");
   BufferedWriter writer = new BufferedWriter(write);
   writer.append(id);
   writer.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * 判断file是否存在于硬盘
  *
  * @param file
  * @return
  */
 private boolean existFile(File file) {
  if (file != null) {
   return file.exists();
  } else {
   return false;
  }
 }

 public static void main(String[] args) throws MessagingException,
   IOException {
  Properties props = new Properties();
  props.setProperty("mail.smtp.host", "smtp.qq.com");
  props.setProperty("mail.smtp.auth", "true");
  Session session = Session.getDefaultInstance(props, null);
  URLName urlname = new URLName("pop3", "pop.qq.com", 110, null,
    "123456@qq.com", "123456");
  Store store = session.getStore(urlname);
  store.connect();
  Folder folder = store.getFolder("INBOX");
  folder.open(Folder.READ_ONLY);
  Message msgs[] = folder.getMessages();
  int count = msgs.length;
  System.out.println("Message Count:" + count);
  MailReciver rm = null;
  for (int i = 0; i < count; i++) {
   rm = new MailReciver((MimeMessage) msgs[i]);
   // 仅获取未读邮件
   if (!rm.isSeen()) {
    rm.recive(msgs[i], i);
   }
  }
 }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics