JAVAMAIL发送邮件

发送邮件:
    1.创建一个邮件会话(MailSession)实例;
    2.使用邮件会话创建一个邮件消息(Message)实例;
    3.设置邮件消息的内容;
    4.使用Tansport.send()方法发送邮件。

  1  /**
  2   * <p>Title: JavaMail</p>
  3   * <p>Description: 发电子邮件</p>
  4   * <p>Copyright: Copyright (c) 2005</p>
  5   * <p>Company: </p>
  6   *  @author  Derek.G
  7   *  @version  1.0
  8    */
  9  import  java.util. * ;
 10  import  javax.mail. * ;
 11  import  javax.mail.internet. * ;
 12  import  java.util.Date;
 13  import  javax.activation. * ;
 14  import  java.io. * ;
 15 
 16  public   class  SendMail {
 17     private  MimeMessage mimeMsg;  // MIME邮件对象
 18     private  Session session;  // 邮件会话对象
 19     private  Properties props;  // 系统属性
 20     private  String username  =   "" // smtp认证用户名和密码
 21     private  String password  =   "" ;
 22     private  Multipart mp;  // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
 23     private   boolean  auth  =   false // smtp验证与否
 24 
 25  public  SendMail(String smtp){
 26  setSmtpHost(smtp);
 27  createMimeMessage();
 28  }
 29 
 30  /**
 31  * 创建系统属性Properties
 32  @param  hostName String
 33  */
 34  public   void  setSmtpHost(String hostName) {
 35  System.out.println( " 设置系统属性:mail.smtp.host =  " + hostName);
 36  if (props  ==   null ) props  =  System.getProperties();  // 获得系统属性对象
 37     props.put( " mail.smtp.host " ,hostName);  // 设置SMTP主机
 38  }
 39 
 40 
 41  /**
 42  * 创建邮件会话对象Session、MIME邮件对象MimeMessage
 43  @return  boolean
 44  */
 45     public   boolean  createMimeMessage(){
 46       try {
 47        System.out.println( " 准备获取邮件会话对象! " );
 48         if (auth){
 49          PopupAuthenticator popupAuthenticator  =   new  PopupAuthenticator(); // 验证类
 50          PasswordAuthentication pop  =  popupAuthenticator.performCheck(username,password);
 51          session  =  Session.getInstance(props,popupAuthenticator);
 52        } else  {
 53          session  =  Session.getInstance(props, null );  // 获得邮件会话对象
 54        }
 55      } catch (Exception e){
 56        System.err.println( " 获取邮件会话对象时发生错误! " + e);
 57         return   false ;
 58      }
 59      System.out.println( " 准备创建MIME邮件对象! " );
 60       try {
 61        mimeMsg  =   new  MimeMessage(session);  // 创建MIME邮件对象
 62        mp  =   new  MimeMultipart();
 63         return   true ;
 64      } catch (Exception e){
 65          System.err.println( " 创建MIME邮件对象失败! " + e);
 66           return   false ;}
 67  }
 68 
 69  /**
 70  * 设置smtp身份认证
 71  @param  need boolean
 72  */
 73     public   void  setNeedAuth( boolean  need) {
 74      System.out.println( " 设置smtp身份认证:mail.smtp.auth =  " + need);
 75       if (props  ==   null )props  =  System.getProperties();
 76       if (need){
 77        props.put( " mail.smtp.auth " , " true " );
 78        auth  =   true ;
 79      } else  props.put( " mail.smtp.auth " , " false " );  
 80    }
 81 
 82  /**
 83  * 设置用户名密码
 84  @param  name String
 85  @param  pass String
 86  */
 87  public   void  setNamePass(String name,String pass) {
 88  username  =  name;
 89  password  =  pass;
 90  }
 91 
 92  /**
 93  * 设置邮件主题
 94  @param  mailSubject String
 95  @return  boolean
 96  */
 97  public   boolean  setSubject(String mailSubject) {
 98  System.out.println( " 设置邮件主题! " );
 99  try {
100    mimeMsg.setSubject(mailSubject);
101     return   true ;
102    } catch (Exception e) {
103      System.err.println( " 设置邮件主题发生错误! " );
104       return   false ;}
105  }
106 
107  /**
108  * 设置邮件体文本内容
109  @param  mailBody String
110  */
111  public   boolean  setBody(String mailBody) {
112  try {
113    BodyPart bp  =   new  MimeBodyPart();
114    bp.setContent( " <meta http-equiv=Content-Type content=text/html; charset=gb2312> " + mailBody, " text/html;charset=GB2312 " );
115    mp.addBodyPart(bp);
116     return   true ;
117      } catch (Exception e){
118       System.err.println( " 设置邮件正文时发生错误! " + e);
119        return   false ;
120    }
121  }
122 
123     /**
124     * 设置邮件附件
125     *  @param  filename String
126     *  @return  boolean
127      */
128     public   boolean  addFileAffix(String filename) {
129 
130      System.out.println( " 增加邮件附件: " + filename);
131 
132       try {
133        BodyPart bp  =   new  MimeBodyPart();
134        FileDataSource fileds  =   new  FileDataSource(filename);
135        bp.setDataHandler( new  DataHandler(fileds));
136        bp.setFileName(fileds.getName());
137        mp.addBodyPart(bp);
138         return   true ;
139      } catch (Exception e){
140        System.err.println( " 增加邮件附件: " + filename + " 发生错误! " + e);
141         return   false ;
142      }
143    }
144 
145     /**
146     * 设置发信人
147     *  @param  from String
148     *  @return  boolean
149      */
150     public   boolean  setFrom(String from) {
151      System.out.println( " 发信人: " + from);
152       try {
153        mimeMsg.setFrom( new  InternetAddress(from));  // 设置发信人
154         return   true ;
155      } catch (Exception e){  return   false ; }
156    }
157 
158     /**
159     * 设置收件人
160     *  @param  to String
161     *  @return  boolean
162      */
163     public   boolean  setTo(String to){
164      System.out.println( " 收件人: " + to);
165       if (to  ==   null ) return   false ;
166       try {
167        mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
168         return   true ;
169      } catch (Exception e){  return   false ; }
170    }
171 
172     /**
173     *  @param  copyto String
174     *  @return  boolean
175      */
176     public   boolean  setCopyTo(String copyto)
177    {
178       if (copyto  ==   null ) return   false ;
179       try {
180        mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
181         return   true ;
182      } catch (Exception e){  return   false ; }
183    }
184 
185     /**
186     * 发邮件操作
187     *  @return  boolean
188      */
189     public   boolean  sendout(){
190           try  {
191            mimeMsg.setContent(mp);
192            mimeMsg.saveChanges();
193            System.out.println( " 正在发送邮件dot.gif. " );
194            mimeMsg.setSentDate( new  Date());
195            Transport transport  =  session.getTransport( " smtp " );
196            transport.connect( (String) props.get( " mail.smtp.host " ), username,password);
197            transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
198            transport.close();
199          //  Transport.send(mimeMsg);
200          } catch  (MessagingException ex) {
201            System.err.println( " 邮件发送失败! " + ex.getMessage());
202             return   false ;
203          }
204        System.out.println( " 邮件发送完成! " );
205         return   true ;
206    }
207  /**
208  * Just do it as this
209  */
210  public   static   void  main(String[] args) {
211    String mailbody  =   " <meta http-equiv=Content-Type content=text/html; charset=gb2312> " +
212         " <div align=center>JAVAMAIL发送邮件测试<img src='usi.png' width='30' height='30'></div> " ;
213    SendMail themail  =   new  SendMail( " smtp.126.com " );
214    themail.setNamePass( " envoydada " , " 12140827 " );  // 登陆帐号密码
215    themail.setNeedAuth( true ); // 设置SMTP是否验证
216     if (themail.setSubject( " JavaMailTest " ==   false return // 设置标题
217     if (themail.setBody(mailbody)  ==   false return // 设置邮件体
218     if (themail.setTo( " derek_g@usish.com " ==   false return ;   // 设置收件人
219     if (themail.setFrom( " envoydada@126.com " ==   false return // 设置发件人
220     if (themail.addFileAffix( " c:\\usi.png " ==   false return // 设置附件
221     if (themail.addFileAffix( " c:\\tmuninst.ini " ==   false return ;
222     if (themail.sendout()  ==   false return // 发出邮件
223    }
224  }
225 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值