Chinaunix首页 | 论坛 | 博客
  • 博客访问: 418464
  • 博文数量: 121
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1393
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-11 12:17
个人简介

www.vibexie.com vibexie@qq.com

文章分类

全部博文(121)

文章存档

2015年(55)

2014年(66)

我的朋友

分类: Java

2015-04-16 18:58:59


注意:首先必须在你的邮箱中开启SMTP服务,浏览器登入你的邮箱,找到相关设置。

取消main方法的注释,发送带抄写人,附件邮件。测试效果效果如下:


MailUtil.java

  1. package com.vibexie.javaMail;

  2. import java.util.Properties;

  3. import javax.activation.DataHandler;
  4. import javax.activation.FileDataSource;
  5. import javax.mail.Address;
  6. import javax.mail.BodyPart;
  7. import javax.mail.Message;
  8. import javax.mail.Multipart;
  9. import javax.mail.Session;
  10. import javax.mail.Transport;
  11. import javax.mail.internet.InternetAddress;
  12. import javax.mail.internet.MimeBodyPart;
  13. import javax.mail.internet.MimeMessage;
  14. import javax.mail.internet.MimeMultipart;
  15.   
  16. /**
  17.  *
  18.  * Title : Mail.java
  19.  * Company: ZhenBot
  20.  * Author : Vibe Xie @
  21.  * Time : Apr 16, 2015 6:29:02 PM
  22.  * Copyright: Copyright (c) 2015
  23.  * Description:    发送邮件的工具类,注意要添加mail.jar和activation.jar两个jar包。
  24.  *                 具体的使用方法在底部注释的main方法中。
  25.  *                 注意:首先必须在你的邮箱中开启SMTP服务,浏览器登入你的邮箱,找到相关设置。
  26.  *                      可以根据你的STMP服务器自己设置SMTP端口,默认是25
  27.  */
  28. public class MailUtil {
  29.     /**
  30.      * 系统属性
  31.      */
  32.     private Properties props;
  33.     
  34.     /**
  35.      * MIME邮件对象
  36.      */
  37.     private MimeMessage mimeMsg;
  38.     
  39.     /**
  40.      * 邮件会话对象
  41.      */
  42.     private Session session;
  43.     
  44.     /**
  45.      * 设置SMTP服务器端口,默认25,有的邮件服务器端口不一样,可以根据需要设置。
  46.      */
  47.     private int SMTP_PORT=25;
  48.     /**
  49.      * smtp是否需要认证
  50.      */
  51.     private boolean needAuth = false;
  52.     
  53.     /**
  54.      * smtp认证用户名
  55.      */
  56.     private String username; //smtp认证用户名
  57.     
  58.     /**
  59.      * smtp认证用户密码
  60.      */
  61.     private String password;
  62.     
  63.     /**
  64.      * Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
  65.      */
  66.     private Multipart mp;
  67.        
  68.     /**
  69.      * 构造器,初始化邮件发送服务器和MIME邮件对象
  70.      * @param smtp 邮件发送服务器
  71.      */
  72.     public MailUtil(String smtp){
  73.         setSmtpHost(smtp);
  74.         createMimeMessage();
  75.     }
  76.   
  77.     /**
  78.      * 设置邮件发送服务器
  79.      * @param hostName String
  80.      */
  81.     public void setSmtpHost(String hostName) {
  82.         System.out.println("设置邮件服务器:mail.smtp.host = "+hostName);
  83.         if(props == null){
  84.             /**
  85.              * 获得系统属性对象
  86.              */
  87.             props = System.getProperties();
  88.         }
  89.         
  90.         /**
  91.          * 设置SMTP主机
  92.          */
  93.         props.put("mail.smtp.host",hostName);
  94.        
  95.         /**
  96.          * 设置SMTP主机端口
  97.          */
  98.         props.put("mail.smtp.port", SMTP_PORT);
  99.     }
  100.   
  101.   
  102.     /**
  103.      * 创建MIME邮件对象
  104.      * @return
  105.      */
  106.     public boolean createMimeMessage()
  107.     {
  108.         try {
  109.             /**
  110.              * 获得邮件会话对象
  111.              */
  112.             session = Session.getDefaultInstance(props,null);
  113.             System.out.println("成功获取邮件会话对象");
  114.         }
  115.         catch(Exception e){
  116.             System.err.println("获取邮件会话对象时发生错误"+e);
  117.             return false;
  118.         }
  119.       
  120.            
  121.         try {
  122.             /**
  123.              * 创建MIME邮件对象
  124.              */
  125.             mimeMsg = new MimeMessage(session);
  126.             mp = new MimeMultipart();
  127.             System.out.println("成功创建MIME邮件对象");
  128.             return true;
  129.         } catch(Exception e){
  130.             System.err.println("创建MIME邮件对象失败"+e);
  131.             return false;
  132.         }
  133.     }
  134.       
  135.     /**
  136.      * 设置SMTP是否需要验证
  137.      * @param need
  138.      */
  139.     public void setNeedAuth(boolean need) {
  140.         System.out.println("设置smtp身份认证:mail.smtp.auth = "+need);
  141.         
  142.         if(props == null){
  143.             props = System.getProperties();
  144.         }
  145.             
  146.         if(need){
  147.             props.put("mail.smtp.auth","true");
  148.         }else{
  149.             props.put("mail.smtp.auth","false");
  150.         }
  151.     }
  152.     
  153.     /**
  154.      * 设置发信人邮箱
  155.      * @param from String
  156.      */
  157.     public boolean setFrom(String from) {
  158.         if(from==null){
  159.             System.out.println("发信人邮箱不能为空,请重新设置!");
  160.             return false;
  161.         }
  162.         
  163.         try{
  164.             /**
  165.              * 设置发信人
  166.              */
  167.             mimeMsg.setFrom(new InternetAddress(from));
  168.             System.out.println("设置发信人邮箱:"+from);
  169.             return true;
  170.         } catch(Exception e) {
  171.             System.out.println("设置发信人邮箱失败!");
  172.             e.printStackTrace();
  173.             return false;
  174.         }
  175.     }
  176.   
  177.     /**
  178.      * 设置发信人用户名和密码
  179.      * @param name
  180.      * @param pass
  181.      */
  182.     public boolean setNamePass(String name,String pass) {
  183.         if(name==null){
  184.             System.out.println("发信人邮箱登录用户名不能为空,请重新设置!");
  185.             return false;
  186.         }
  187.         
  188.         if(pass==null){
  189.             System.out.println("发信人邮箱登录密码不能为空,请重新设置!");
  190.             return false;
  191.         }
  192.         
  193.         username = name;
  194.         password = pass;
  195.         System.out.println("设置发信人邮箱登录用户名:"+name+" 并设置密码成功!");
  196.         
  197.         return true;
  198.     }
  199.     
  200.     /**
  201.      * 设置收信人邮箱
  202.      * @param to String
  203.      */
  204.     public boolean setTo(String to){
  205.         if(to == null){
  206.             System.out.println("收信人不能未空,请重新设置!");
  207.             return false;
  208.         }
  209.         
  210.         try{
  211.             mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
  212.             System.out.println("设置收信人邮箱:"+to);
  213.             return true;
  214.         } catch(Exception e) {
  215.             System.out.println("设置收信人邮箱失败!");
  216.             e.printStackTrace();
  217.             return false;
  218.         }
  219.     }
  220.       
  221.     /**
  222.      * 设置抄送人
  223.      * @param copyto String
  224.      */
  225.     public boolean setCopyTo(String copyto)
  226.     {
  227.         if(copyto == null){
  228.             System.out.println("抄送人不能未空,请重新设置!");
  229.             return false;
  230.         }
  231.         
  232.         try{
  233.             mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
  234.             System.out.println("设置抄信人邮箱:"+copyto);
  235.             return true;
  236.         }catch(Exception e){
  237.             e.printStackTrace();
  238.             return false;
  239.         }
  240.     }
  241.   
  242.     /**
  243.      * 设置邮件主题
  244.      * @param mailSubject
  245.      * @return
  246.      */
  247.     public boolean setSubject(String mailSubject) {
  248.         if(mailSubject==null){
  249.             System.out.println("邮件主题不能为空,请重新设置!");
  250.             return false;
  251.         }
  252.         
  253.         try{
  254.             mimeMsg.setSubject(mailSubject,"UTF-8");
  255.             System.out.println("设置邮件主题:"+mailSubject);
  256.             return true;
  257.         }catch(Exception e) {
  258.             System.err.println("设置邮件主题发生错误!");
  259.             e.printStackTrace();
  260.             return false;
  261.         }
  262.     }
  263.       
  264.     /**
  265.      * 设置邮件正文
  266.      * @param mailBody String
  267.      */
  268.     public boolean setBody(String mailBody) {
  269.         if(mailBody==null){
  270.             System.out.println("邮件正文不能为空,请重新设置!");
  271.             return false;
  272.         }
  273.         
  274.         try{
  275.             BodyPart bp = new MimeBodyPart();
  276.             bp.setContent(""+mailBody,"text/html;charset=UTF-8");
  277.             mp.addBodyPart(bp);
  278.             System.out.println("设置邮件正文:"+mailBody);
  279.             return true;
  280.         } catch(Exception e){
  281.             System.err.println("设置邮件正文时发生错误!"+e);
  282.             return false;
  283.         }
  284.     }
  285.     /**
  286.      * 添加附件
  287.      * @param filename String
  288.      */
  289.     public boolean addFileAffix(String filename) {
  290.       
  291.         System.out.println("设置邮件附件:"+filename);
  292.         try{
  293.             BodyPart bp = new MimeBodyPart();
  294.             FileDataSource fileds = new FileDataSource(filename);
  295.             bp.setDataHandler(new DataHandler(fileds));
  296.             bp.setFileName(fileds.getName());
  297.             mp.addBodyPart(bp);
  298.             return true;
  299.         } catch(Exception e){
  300.             System.err.println("增加邮件附件:"+filename+"发生错误!"+e);
  301.             e.printStackTrace();
  302.             return false;
  303.         }
  304.     }
  305.       

  306.     /***
  307.      * 发送邮件方法
  308.      * @param withCopyMan 是否带抄送人
  309.      * @return
  310.      */
  311.     public boolean sendOut(boolean withCopyMan)
  312.     {
  313.         try{
  314.             mimeMsg.setContent(mp);
  315.             mimeMsg.saveChanges();
  316.             System.out.println("正在发送邮件....");
  317.               
  318.             Session mailSession = Session.getInstance(props,null);
  319.             Transport transport = mailSession.getTransport("smtp");
  320.             transport.connect((String)props.get("mail.smtp.host"),username,password);
  321.             transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
  322.             
  323.             /**
  324.              * 带抄送人
  325.              */
  326.             if(withCopyMan){
  327.                 transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC));
  328.             }
  329.            
  330.             System.out.println("发送邮件成功!");
  331.             transport.close();
  332.               
  333.             return true;
  334.         } catch(Exception e) {
  335.             System.err.println("邮件发送失败!"+e);
  336.             e.printStackTrace();
  337.             return false;
  338.         }
  339.     }
  340.     
  341.     /***
  342.      * 发送普通邮件
  343.      * @param smtp
  344.      * @param from
  345.      * @param username
  346.      * @param password
  347.      * @param to
  348.      * @param subject
  349.      * @param content
  350.      * @return
  351.      */
  352.     public static boolean sendCommonEmail(String smtp,String from,String username,String password,String to,String subject,String content) {
  353.         MailUtil theMail = new MailUtil(smtp);
  354.         theMail.setNeedAuth(true); //需要验证
  355.         
  356.         if(!theMail.setFrom(from)) return false;
  357.         if(!theMail.setNamePass(username,password)) return false;
  358.         if(!theMail.setTo(to)) return false;
  359.         if(!theMail.setSubject(subject)) return false;
  360.         if(!theMail.setBody(content)) return false;
  361.         
  362.         if(!theMail.sendOut(false)) return false;
  363.         
  364.         return true;
  365.     }
  366.     
  367.     /***
  368.      * 发送带抄送人邮件
  369.      * @param smtp
  370.      * @param from
  371.      * @param username
  372.      * @param password
  373.      * @param to
  374.      * @param copyto
  375.      * @param subject
  376.      * @param content
  377.      * @return
  378.      */
  379.     public static boolean sendEmailWithCopyMan(String smtp,String from,String username,String password,String to,String copyto,String subject,String content) {
  380.         MailUtil theMail = new MailUtil(smtp);
  381.         theMail.setNeedAuth(true); //需要验证
  382.          
  383.         if(!theMail.setFrom(from)) return false;
  384.         if(!theMail.setNamePass(username,password)) return false;
  385.         if(!theMail.setTo(to)) return false;
  386.         if(!theMail.setCopyTo(copyto)) return false;
  387.         if(!theMail.setSubject(subject)) return false;
  388.         if(!theMail.setBody(content)) return false;
  389.         
  390.         if(!theMail.sendOut(true)) return false;
  391.         
  392.         return true;
  393.     }
  394.     
  395.     /***
  396.      * 发送带附件邮件
  397.      * @param smtp
  398.      * @param from
  399.      * @param password
  400.      * @param filename
  401.      * @param to
  402.      * @param subject
  403.      * @param content
  404.      * @param username
  405.      * @return
  406.      */
  407.     public static boolean sendEmailWithAppendix(String smtp,String from,String password,String filename,String to,String subject,String content,String username) {
  408.         MailUtil theMail = new MailUtil(smtp);
  409.         theMail.setNeedAuth(true); //需要验证
  410.   
  411.         if(!theMail.setFrom(from)) return false;
  412.         if(!theMail.setNamePass(username,password)) return false;
  413.         if(!theMail.setTo(to)) return false;
  414.         if(!theMail.setSubject(subject)) return false;
  415.         if(!theMail.setBody(content)) return false;
  416.         if(!theMail.addFileAffix(filename)) return false;
  417.         
  418.         if(!theMail.sendOut(false)) return false;
  419.         
  420.         return true;
  421.     }
  422.     
  423.     /***
  424.      * 发送带抄送人和附件邮件
  425.      * @param smtp
  426.      * @param from
  427.      * @param username
  428.      * @param password
  429.      * @param to
  430.      * @param copyto
  431.      * @param subject
  432.      * @param content
  433.      * @param filename
  434.      * @return
  435.      */
  436.     public static boolean sendEmailWithCopyManAndAppendix(String smtp,String from,String username,String password,String to,String copyto,String subject,String content,String filename) {
  437.         MailUtil theMail = new MailUtil(smtp);
  438.         theMail.setNeedAuth(true); //需要验证
  439.           
  440.         if(!theMail.setFrom(from)) return false;
  441.         if(!theMail.setNamePass(username,password)) return false;
  442.         if(!theMail.setTo(to)) return false;
  443.         if(!theMail.setCopyTo(copyto)) return false;
  444.         if(!theMail.setSubject(subject)) return false;
  445.         if(!theMail.setBody(content)) return false;
  446.         if(!theMail.addFileAffix(filename)) return false;
  447.         
  448.         if(!theMail.sendOut(true)) return false;
  449.         
  450.         return true;
  451.     }

  452. // /**
  453. // * 测试
  454. // * @param args
  455. // */
  456. // public static void main(String[] args){
  457. //     /**
  458. //      * SMTP服务器
  459. //      */
  460. // String smtp = "smtp.mxhichina.com";
  461. // /**
  462. // * 发信人邮箱
  463. // */
  464. // String from = "admin@vibexie.com";
  465. // /**
  466. // * 发信人邮箱用户名
  467. // */
  468. // String username="admin@vibexie.com";
  469. // /**
  470. // * 发信人邮箱密码
  471. // */
  472. // String password="XXXXXXXX";
  473. // /**
  474. // * 收信人邮箱
  475. // */
  476. // String to = "vibexie@qq.com";
  477. // /**
  478. // * 抄送人邮箱
  479. // */
  480. // String copyto = "vibexie@qq.com";
  481. // /**
  482. // * 邮件主题
  483. // */
  484. // String subject = "邮件主题";
  485. // /**
  486. // * 邮件内容
  487. // */
  488. // String content = "邮件内容";
  489. // /**
  490. // * 附件路径,如:home/vibexie/email.text
  491. // */
  492. // String filename = "/home/vibexie/mail.jar";
  493. //
  494. // /**
  495. // * 发送普通邮件
  496. // */
  497. // //MailUtil.sendCommonEmail(smtp, from, username, password, to, subject, content);
  498. //
  499. // /**
  500. // * 发送带抄送人邮件
  501. // */
  502. // //MailUtil.sendEmailWithCopyMan(smtp, from, username, password, to, copyto, subject, content);
  503. //
  504. // /**
  505. // * 发送带附件邮件
  506. // */
  507. // //MailUtil.sendEmailWithAppendix(smtp, from, password, filename, copyto, subject, content, username);
  508. //
  509. // /**
  510. // * 发送发送带抄送人和附件邮件
  511. // */
  512. // MailUtil.sendEmailWithCopyManAndAppendix(smtp, from, username, password, to, copyto, subject, content, filename);
  513. // }
  514.     
  515.     
  516. // /**
  517. // * 精简版发送邮件
  518. // */
  519. // import java.io.UnsupportedEncodingException;
  520. // import java.util.Date;
  521. // import java.util.Properties;
  522. // import javax.mail.Message;
  523. // import javax.mail.MessagingException;
  524. // import javax.mail.NoSuchProviderException;
  525. // import javax.mail.Session;
  526. // import javax.mail.Transport;
  527. // import javax.mail.internet.InternetAddress;
  528. // import javax.mail.internet.MimeMessage;
  529. //
  530. // public class MailUtil {
  531. //
  532. // static int port = 25;
  533. //
  534. // static String server = "smtp.sina.com";//邮件服务器mail.cpip.net.cn
  535. //
  536. // static String from = "张三";//发送者,显示的发件人名字
  537. //
  538. // static String user = "??????@sina.com";//发送者邮箱地址
  539. //
  540. // static String password = "??????????";//密码
  541. //
  542. //
  543. // public static void sendEmail(String email, String subject, String body) throws UnsupportedEncodingException {
  544. // try {
  545. // Properties props = new Properties();
  546. // props.put("mail.smtp.host", server);
  547. // props.put("mail.smtp.port", String.valueOf(port));
  548. // props.put("mail.smtp.auth", "true");
  549. // Transport transport = null;
  550. // Session session = Session.getDefaultInstance(props, null);
  551. // transport = session.getTransport("smtp");
  552. // transport.connect(server, user, password);
  553. // MimeMessage msg = new MimeMessage(session);
  554. // msg.setSentDate(new Date());
  555. // InternetAddress fromAddress = new InternetAddress(user,from,"UTF-8");
  556. // msg.setFrom(fromAddress);
  557. // InternetAddress[] toAddress = new InternetAddress[1];
  558. // toAddress[0] = new InternetAddress(email);
  559. // msg.setRecipients(Message.RecipientType.TO, toAddress);
  560. // msg.setSubject(subject, "UTF-8");
  561. // msg.setText(body, "UTF-8");
  562. // msg.saveChanges();
  563. // transport.sendMessage(msg, msg.getAllRecipients());
  564. // } catch (NoSuchProviderException e) {
  565. // e.printStackTrace();
  566. // } catch (MessagingException e) {
  567. // e.printStackTrace();
  568. // }
  569. // }
  570. // public static void main(String args[]) throws UnsupportedEncodingException
  571. // {
  572. //
  573. // sendEmail("??????@sina.com","邮件测试","hello");//收件人
  574. // System.out.println("ok");
  575. // }
  576. // }
  577.     
  578. }


阅读(2239) | 评论(0) | 转发(0) |
0

上一篇:自定义流布局

下一篇:Servlet框架

给主人留下些什么吧!~~