---
title: "javamail使用方法"
author: "wxiaoneng"
date: "2011-08-29T11:14:43Z"
tags: []
categories: ["编程语言"]
slug: "javamail"
draft: false
lastmod: "2011-08-29T11:14:43Z"
id: 1160182
url: "https://wxiaoneng.iteye.com/blog/1160182"
---

下面是一段用Java mail API发带附件邮件的方法，附件是读的硬盘上的文件，你参考下吧   
String message="Mail send OK！";   
  Session session=null;   
  Properties props = System.getProperties();   
  props.put("mail.smtp.host", smtpServer);   
  if(ifAuth){ //the mail server ask auth   
  props.put("mail.smtp.auth","true");   
  MailAuth smtpAuth=new MailAuth(username,password);   
  session=Session.getDefaultInstance(props, smtpAuth);   
  }else{   
  props.put("mail.smtp.auth","false");   
  session=Session.getDefaultInstance(props, null);   
  }   
  session.setDebug(isDebug);   

  Transport trans = null;
  try {   
  Message msg = new MimeMessage(session);   
  try{   
  Address from_address;
  if (displayName == null)
  from_address = new InternetAddress(from);
  else  
  from_address = new InternetAddress(from, displayName);
  msg.setFrom(from_address);   
  }catch(java.io.UnsupportedEncodingException e){   
  e.printStackTrace();   
  }   
  //InternetAddress address={new InternetAddress(to)};   
  InternetAddress address= InternetAddress.parse(to);   
  msg.setRecipients(Message.RecipientType.TO,address);   
  msg.setSubject(subject);   
    
  if (cc != null) {
  InternetAddress ccAddr= InternetAddress.parse(cc);   
  msg.setRecipients(Message.RecipientType.CC, ccAddr);
  }
    
    
  Multipart mp = new MimeMultipart();   
  MimeBodyPart mbp = new MimeBodyPart();   
  //mbp.setContent(content.toString(), "text/html"); //;charset=gb2312");   
  mbp.setContent(content.toString(), "text/plain"); //;charset=gb2312");   
  mp.addBodyPart(mbp);   
  if(!file.isEmpty()){//have attachment
  Enumeration efile=file.elements();   
  while(efile.hasMoreElements()){   
  mbp=new MimeBodyPart();   
  filename=efile.nextElement().toString(); //get each attachment name   
  FileDataSource fds=new FileDataSource(filename); //get the file data source
  mbp.setDataHandler(new DataHandler(fds)); //get the attachment content   
  mbp.setFileName(fds.getName()); //get the file name and include to content
  mp.addBodyPart(mbp);   
  }   
  file.removeAllElements();   
  }   
  msg.setContent(mp); // add the Multipart into mail   
  msg.setSentDate(new Date()); //set the date in mail header   

  // send   
  msg.saveChanges();   
  trans = session.getTransport("smtp");   
  trans.connect(smtpServer, username, password);   
  trans.sendMessage(msg, msg.getAllRecipients());   
  trans.close();   
    
  }catch(AuthenticationFailedException e){   
  map.put("state", "failed");   
  message="Mail send fail！Error caused：auth error!\n";   
  e.printStackTrace();   
  }catch (MessagingException e) {   
  message="Mail send fail！Error caused：\n"+e.getMessage();   
  map.put("state", "failed");   
  e.printStackTrace();   
  Exception ex = null;   
  if ((ex = e.getNextException()) != null) {   
  System.out.println(ex.toString());   
  ex.printStackTrace();   
  }   
  }