java通过qq邮箱发送邮件

闲来无事,想了解一下java怎么发送邮件,然后百度了一下,看看别人的样例,自己整合了一套代码。

jar包的话只需要下一个:mail.jar;从百度云盘下载:

https://pan.baidu.com/s/1c2yvL2w

里面也有工程代码,下面我主要讲讲具体是怎么实现的。


首先因为是针对qq邮箱,所以对别的邮箱要有稍稍改动。其实我一开始是想写成163邮箱的,因为限制太大,老是被认为垃圾邮件发布出去,所以就用qq邮箱了。

前期准备:先要到qq邮箱的设置下,点击账户选项,找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,然后开启POP3/SMTP服务。接着就会获取一段授权密码。记下来等下发邮件需要用到。

代码如下:解释在注释下

[java]  view plain  copy
  1. import java.io.UnsupportedEncodingException;  
  2. import java.util.Date;  
  3. import java.util.Properties;  
  4.   
  5. import javax.activation.DataHandler;  
  6. import javax.activation.FileDataSource;  
  7. import javax.mail.Authenticator;  
  8. import javax.mail.BodyPart;  
  9. import javax.mail.Message.RecipientType;  
  10. import javax.mail.MessagingException;  
  11. import javax.mail.Multipart;  
  12. import javax.mail.PasswordAuthentication;  
  13. import javax.mail.Session;  
  14. import javax.mail.Transport;  
  15. import javax.mail.internet.InternetAddress;  
  16. import javax.mail.internet.MimeBodyPart;  
  17. import javax.mail.internet.MimeMessage;  
  18. import javax.mail.internet.MimeMultipart;  
  19. import javax.mail.internet.MimeUtility;  
  20.   
  21. /** 
  22.  * 发送邮件的测试程序(适用qq邮箱) 
  23.  * 通过本人的qq邮箱: xxx@qq.com 发送邮件 
  24.  * @author miaoch 
  25.  *  
  26.  */  
  27. public class MailTest {  
  28.   
  29.     //发送的邮箱 内部代码只适用qq邮箱  
  30.     private static final String USER = "xxx@qq.com";  
  31.     //授权密码 通过QQ邮箱设置->账户->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务->开启POP3/SMTP服务获取  
  32.     private static final String PWD = "wtyvpggofkubbhci";  
  33.       
  34.     private String[] to;  
  35.     private String[] cc;//抄送  
  36.     private String[] bcc;//密送  
  37.     private String[] fileList;//附件  
  38.     private String subject;//主题  
  39.     private String content;//内容,可以用html语言写  
  40.     public void sendMessage() throws MessagingException, UnsupportedEncodingException {  
  41.         // 配置发送邮件的环境属性  
  42.         final Properties props = new Properties();  
  43.         //下面两段代码是设置ssl和端口,不设置发送不出去。  
  44.         props.setProperty("mail.smtp.socketFactory.class""javax.net.ssl.SSLSocketFactory");  
  45.         //props.setProperty("mail.smtp.port", "465");  
  46.         props.setProperty("mail.smtp.socketFactory.port""465");  
  47.         // 表示SMTP发送邮件,需要进行身份验证  
  48.         props.setProperty("mail.transport.protocol""smtp");// 设置传输协议  
  49.         props.put("mail.smtp.auth""true");  
  50.         props.put("mail.smtp.host""smtp.qq.com");//QQ邮箱的服务器 如果是企业邮箱或者其他邮箱得更换该服务器地址  
  51.         // 发件人的账号  
  52.         props.put("mail.user", USER);  
  53.         // 访问SMTP服务时需要提供的密码   
  54.         props.put("mail.password", PWD);  
  55.   
  56.         // 构建授权信息,用于进行SMTP进行身份验证  
  57.         Authenticator authenticator = new Authenticator() {  
  58.             @Override  
  59.             protected PasswordAuthentication getPasswordAuthentication() {  
  60.                 // 用户名、密码  
  61.                 String userName = props.getProperty("mail.user");  
  62.                 String password = props.getProperty("mail.password");  
  63.                 return new PasswordAuthentication(userName, password);  
  64.             }  
  65.         };  
  66.         // 使用环境属性和授权信息,创建邮件会话  
  67.         Session mailSession = Session.getInstance(props, authenticator);  
  68.         // 创建邮件消息  
  69.         MimeMessage message = new MimeMessage(mailSession);  
  70.         BodyPart messageBodyPart = new MimeBodyPart();   
  71.         Multipart multipart = new MimeMultipart();   
  72.         // 设置发件人  
  73.         InternetAddress form = new InternetAddress(  
  74.                 props.getProperty("mail.user"));  
  75.         message.setFrom(form);  
  76.         //发送  
  77.         if (to != null) {   
  78.             String toList = getMailList(to);   
  79.             InternetAddress[] iaToList = new InternetAddress().parse(toList);   
  80.             message.setRecipients(RecipientType.TO, iaToList); // 收件人   
  81.         }   
  82.         //抄送   
  83.         if (cc != null) {   
  84.             String toListcc = getMailList(cc);   
  85.             InternetAddress[] iaToListcc = new InternetAddress().parse(toListcc);   
  86.             message.setRecipients(RecipientType.CC, iaToListcc); // 抄送人   
  87.         }   
  88.         //密送   
  89.         if (bcc != null) {   
  90.             String toListbcc = getMailList(bcc);   
  91.             InternetAddress[] iaToListbcc = new InternetAddress().parse(toListbcc);   
  92.             message.setRecipients(RecipientType.BCC, iaToListbcc); // 密送人   
  93.         }   
  94.         message.setSentDate(new Date()); // 发送日期 该日期可以随意写,你可以写上昨天的日期(效果很特别,亲测,有兴趣可以试试),或者抽象出来形成一个参数。  
  95.         message.setSubject(subject); // 主题   
  96.         message.setText(content); // 内容   
  97.         //显示以html格式的文本内容   
  98.         messageBodyPart.setContent(content,"text/html;charset=utf-8");   
  99.         multipart.addBodyPart(messageBodyPart);   
  100.         //保存多个附件   
  101.         if(fileList!=null){   
  102.             addTach(fileList, multipart);   
  103.         }   
  104.         message.setContent(multipart);   
  105.         // 发送邮件  
  106.         Transport.send(message);  
  107.     }  
  108.   
  109.     public void setTo(String[] to) {  
  110.         this.to = to;  
  111.     }  
  112.   
  113.     public void setCc(String[] cc) {  
  114.         this.cc = cc;  
  115.     }  
  116.   
  117.     public void setBcc(String[] bcc) {  
  118.         this.bcc = bcc;  
  119.     }  
  120.       
  121.     public void setSubject(String subject) {  
  122.         this.subject = subject;  
  123.     }  
  124.       
  125.     public void setContent(String content) {  
  126.         this.content = content;  
  127.     }  
  128.       
  129.     public void setFileList(String[] fileList) {  
  130.         this.fileList = fileList;  
  131.     }  
  132.       
  133.     private String getMailList(String[] mailArray) {   
  134.         StringBuffer toList = new StringBuffer();   
  135.         int length = mailArray.length;   
  136.         if (mailArray != null && length < 2) {   
  137.             toList.append(mailArray[0]);   
  138.         } else {   
  139.             for (int i = 0; i < length; i++) {   
  140.                 toList.append(mailArray[i]);   
  141.                 if (i != (length - 1)) {   
  142.                     toList.append(",");   
  143.                 }   
  144.             }   
  145.         }   
  146.         return toList.toString();   
  147.     }   
  148.       
  149.     //添加多个附件   
  150.     public void addTach(String fileList[], Multipart multipart) throws MessagingException, UnsupportedEncodingException {   
  151.         for (int index = 0; index < fileList.length; index++) {   
  152.              MimeBodyPart mailArchieve = new MimeBodyPart();   
  153.              FileDataSource fds = new FileDataSource(fileList[index]);   
  154.              mailArchieve.setDataHandler(new DataHandler(fds));   
  155.              mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"UTF-8","B"));   
  156.              multipart.addBodyPart(mailArchieve);   
  157.         }     
  158.     }  
  159.       
  160.     //以下是演示demo  
  161.     public static void main(String args[]) {  
  162.         MailTest mail = new MailTest();  
  163.         mail.setSubject("这个是标题");  
  164.         mail.setContent("这个是内容");  
  165.         //收件人 可以发给其他邮箱(163等) 下同  
  166.         mail.setTo(new String[] {"xxx@qq.com","xxx@qq.com"});  
  167.         //抄送  
  168.         mail.setCc(new String[] {"xxx@qq.com","xxx@qq.com"});  
  169.         //密送  
  170.         mail.setBcc(new String[] {"xxx@qq.com","xxx@qq.com"});  
  171.         //发送附件列表 可以写绝对路径 也可以写相对路径(起点是项目根目录)  
  172.         mail.setFileList(new String[] {"file\\附件1.txt","file\\附件2.txt"});  
  173.         //发送邮件  
  174.         try {  
  175.             mail.sendMessage();  
  176.             System.out.println("发送邮件成功!");  
  177.         } catch (Exception e) {  
  178.             System.out.println("发送邮件失败!");  
  179.             e.printStackTrace();  
  180.         }  
  181.     }  
  182. }  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值