`

java send email

    博客分类:
  • java
阅读更多
   1. package com._100fly.javamail; 
   2.  
   3. import java.util.Properties; 
   4.  
   5. import javax.mail.Authenticator; 
   6. import javax.mail.Message; 
   7. import javax.mail.MessagingException; 
   8. import javax.mail.PasswordAuthentication; 
   9. import javax.mail.Session; 
  10. import javax.mail.Transport; 
  11. import javax.mail.Message.RecipientType; 
  12. import javax.mail.internet.AddressException; 
  13. import javax.mail.internet.InternetAddress; 
  14. import javax.mail.internet.MimeMessage; 
  15.  
  16. public class SencMail { 
  17.  
  18.     /**
  19.      * @param args
  20.      * @throws MessagingException 
  21.      * @throws AddressException 
  22.      * @throws MessagingException 
  23.      */ 
  24.     public static void main(String[] args) throws AddressException, MessagingException { 
  25.         // TODO Auto-generated method stub 
  26.         Properties props = new Properties(); 
  27.          
  28.         //两个属性必须配置 
  29.          
  30.         //连哪种服务器 
  31.         props.setProperty("mail.transport.protocol", "smtp"); 
  32.         //设置需要验证(给提供用户名、密码) 
  33.         props.setProperty("mail.smtp.auth", "true"); 
  34.         props.setProperty("mail.host", "smtp.gmail.com"); 
  35.         Session session = Session.getInstance(props, 
  36.  
  37.                 //返回验证信息的内部类 
  38.                 new Authenticator() 
  39.                 { 
  40.              
  41.                     protected PasswordAuthentication getPasswordAuthentication() 
  42.                     { 
  43.                          
  44.                         return new PasswordAuthentication("mengzhongyouni@gmail.com","zeng@4717"); 
  45.                     } 
  46.                 } 
  47.          
  48.         ); 
  49.          
  50.         session.setDebug(true); 
  51.          
  52.         Message msg = new MimeMessage(session); 
  53.         try { 
  54.             msg.setFrom(new InternetAddress("hello@gmail.com")); 
  55.             msg.setSubject("中文主题"); 
  56.             msg.setRecipients(RecipientType.TO, InternetAddress.parse("1260128980@qq.com,mengzhongyouni@gmail.com")); 
  57.             msg.setContent("<span style='color:red'>我是以HTML代码解析出来的</span>", "text/html;charset=gbk"); 
  58.              
  59.             //没有指定收件人 会在msg里面去找 
  60.             Transport.send(msg); 
  61.         } catch (AddressException e) { 
  62.             // TODO Auto-generated catch block 
  63.             e.printStackTrace(); 
  64.         } catch (MessagingException e) { 
  65.             // TODO Auto-generated catch block 
  66.             e.printStackTrace(); 
  67.         } 
  68.          
  69.     } 
  70.  
  71. } 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics