`

java实现发送邮件功能

 
阅读更多
package util;
import java.io.InputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
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;
/***
 *  Send edm to mail
 *  Jerry.li
 *  2012-05-02
 */
public class EdmMail {
  
     private static String MAIL_TITLE = null;
     private String mailServerHost = "";      
     private String fromAddress = ""; //发送人邮箱地址
     private String toAddress = "";   //收件人邮箱地址
     private MimeMessage mimemsg;     //Mime邮件对象
     private Session session;         //邮件会话对象
     private Properties properties;   //系统属性
     private Multipart part;          //Multipart对象:邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
     private String username = "";    //设置smtp的用户名
     private String password = "";    //设置smtp的密码
     private String profile = "search.properties";
      
      
     private EdmMail(){
      getValues();
      setSmtpHost(mailServerHost);
      getMailSession();
     }
      
     public EdmMail(String sub){
      this();
      MAIL_TITLE = sub;
     }
      
     private boolean getValues(){
      Properties proties = null;
      InputStream input = null;
      try {
       input = EdmMail.class.getClassLoader().getResourceAsStream(profile);
    proties = new Properties();
    proties.load(input);
    mailServerHost = proties.getProperty("MAIL_HOST");
    fromAddress = proties.getProperty("MAIL_FROM");
    username = proties.getProperty("MAIL_USERNAME");
    password = proties.getProperty("MAIL_PASSWORD");
    toAddress = proties.getProperty("MAILTO_LIST");
    return true;
   } catch (Exception e) {
             System.out.println("读取配置文件出错!"+e);
             return false;
   }
     }
      
     /***
      * 设置SMTP主机
      */
  private void setSmtpHost(String mailhost){
      if(properties == null){
       properties = System.getProperties(); //获得系统属性
      }
      properties.setProperty("mail.smtp.host", mailhost);
     }
   
  /***
   *  获得邮件会话对象
   *  创建MimeMessage对象
   */
  private boolean getMailSession(){
   try {
    session = Session.getDefaultInstance(properties,null);
   } catch (Exception e) {
    System.out.println("获取邮件会话对象出错,原因:"+e);
    return false;
   }
   try {
    mimemsg = new MimeMessage(session);
    part = new MimeMultipart();
    return true;
   } catch (Exception e) {
             System.out.println("创建Mime邮件对象出错,原因:"+e);
             return false;
   }
  }
   
  /***
   * 设置smtp身份认证
   * mail.smtp.auth = true
   */
  private void setSmtpAuth(boolean bool){
      if(properties == null){
       properties = System.getProperties(); //获得系统属性
      }
      if(bool){
       properties.put("mail.smtp.auth", "true");
      }else{
       properties.put("mail.smtp.auth", "false");
      }
  }
   
  /***
   *  设置邮件的主题
   */
     private boolean setMailSub(String mailsubject){
      try {
       mimemsg.setSubject(mailsubject, "GBK");
    return true;
   } catch (Exception e) {
    System.out.println("设置邮件标题出错,原因:"+e);
    return false;
   }
     }
      
     /***
      * 设置邮件体格式
      */
     private boolean setMailBody(String mailBody){
      BodyPart bdyPart = new MimeBodyPart();
      try {
    bdyPart.setContent(mailBody, "text/html;charset=GBK");
    part.addBodyPart(bdyPart);
    return true;
   } catch (Exception e) {
    System.out.println("设置邮件体格式出错,原因:"+e);
    return false;
   }
     }
      
     /***
      *  添加邮件附件
      */
      
     private boolean addAttach(String filePath){
      BodyPart bdy = new MimeBodyPart();
      try {
       FileDataSource dataSource = new FileDataSource(filePath);
    bdy.setDataHandler(new DataHandler(dataSource));
    bdy.setFileName(dataSource.getName());   //设置附件名
    part.addBodyPart(bdy);
    return true;
   } catch (Exception e) {
    System.out.println("添加附件:"+filePath+"出错,原因:"+e);
    return false;
   }
     }
      
     /***
      *  设置邮件发送人
      */
     private boolean setMailFrom(String from){
      try {
       mimemsg.setFrom(new InternetAddress(from));
    return true;
   } catch (Exception e) {
    System.out.println("设置邮件发送人:"+from+"出错,原因:"+e);
    return false;
   }
     }
      
     /***
      *  设置邮件接收人
      */
     private boolean setMailTo(String mailto){
      if(mailto == null){
       return false;
      }
      try {
       mimemsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailto));
    return true;
      }catch (Exception e) {
            System.out.println("设置邮件接收人:"+mailto+"出错,原因:"+e);
            return false;
      }
     }
      
     /***
      *  发送邮件
      */
     private boolean sendout(){
      try {
       mimemsg.setContent(part);
       mimemsg.saveChanges();
    System.out.println("开始发送邮件......");
    Session mailSession = Session.getInstance(properties, null);
    Transport tsport = mailSession.getTransport("smtp");
    tsport.connect((String)properties.get("mail.smtp.host"), username, password);
    tsport.sendMessage(mimemsg, mimemsg.getRecipients(Message.RecipientType.TO));
    tsport.close();
    System.out.println("发送邮件成功!");
    return true;
   } catch (Exception e) {
             System.out.println("发送邮件出错原因:"+e);
             return false;
   }
     }
      
     //
     public void sendMail(String fileAttach){
      //拼接整个邮件的内容
      StringBuffer content = new StringBuffer();
      //头部
      content.append("<html>");
      content.append("<head><META content='text/html; charset=gbk' http-equiv=Content-Type>");
      content.append("<META name=GENERATOR content='MSHTML 8.00.6001.18702'>");
      content.append("<style type='text/css'>");
      content.append(".STYLE1 {color: #000000}");
      content.append("TABLE {FONT-SIZE: 12px; COLOR: #444444;LINE-HEIGHT: 14px; FONT-FAMILY: '宋体', 'Arial'; TEXT-DECORATION: none;}");
      content.append(".STYLE3 { font-size: 13px;color: #FD9800; font-weight: bold;}");
      content.append("</style>");
      content.append("</head>");
      //显示邮件内容
      content.append("<body>");
      content.append("<table width='749px' align='left'>");
      content.append("<tr><td width='749' height='10px'></td></tr>");
      content.append("<tr><td><p align='left'><font size=2>for test!</font></p></td></tr>");
      content.append("</table>");
      //content.append("");
      content.append("</body>");
      content.append("</html>");
       
      System.out.println("content********"+content);
       
      setSmtpAuth(false);
      if(setMailSub(MAIL_TITLE) == false){
       return;
      }
      if(setMailBody(content.toString()) == false){
       return;
      }
      if(setMailTo(toAddress) == false){
       return;
      }
      if(setMailFrom(fromAddress) == false){
       return;
      }
       
      if(addAttach(fileAttach) == false){
       return;
      }
      if(sendout()== false){
       return;
      }
     }
      
     public static void main(String[] args) {
      EdmMail m = new EdmMail("test");
      //附件的位置
      m.sendMail("D:\\workspace\\test.xls");
  }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics