600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > javamail实现用普通QQ邮箱发送邮件

javamail实现用普通QQ邮箱发送邮件

时间:2020-10-26 10:13:41

相关推荐

javamail实现用普通QQ邮箱发送邮件

转载出处:/Coding_One/article/details/51354456

本人最近在写一个Android项目,用户注册的时候想用邮箱验证的方式,于是就需要在服务器端发送电子邮件给新注册用户,邮件内容中包含一个 链接, 当用户点击这个链接将 登录到服务器 的验证逻辑。本人在网上找了很多代码,可能由于是很久以前的了,各大邮箱的规范 什么的都发生改变,所以总是出现一些问题。庆幸 的是,最后还是实现了。

这是我用大号 发给小号 和另外一个 163 邮箱的 测试邮件

首先,发一个连接,我在困扰了了两天之后,终于得到了这位前辈的解救,我发的代码基本上也都是他的源码,只是有几处关键地方的改动。

点击

当然,把前辈的代码 copy 直接运行肯定是不行的。

废话不说,直接上源码吧:

1、发送邮件的类:

package com.pleasurewithriding.assistantclass;import java.io.File;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.Date;import java.util.List;import java.util.Map;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.Address;import javax.mail.Authenticator;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.PasswordAuthentication;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.internet.MimeUtility;public class SendMail {private String username = null;private String password = null;private Authenticator auth = null;private MimeMessage mimeMessage =null;private Properties pros = null;private Multipart multipart = null;private BodyPart bodypart= null;/*** 初始化账号密码并验证* 创建MimeMessage对象* 发送邮件必须的步骤:1* @param username* @param password*/public SendMail(String username,String password){this.username = username;this.password = password;} /*** 初始化MimeMessage对象* 发送邮件必须的步骤:3*/public void initMessage(){this.auth = new Email_Autherticator();Session session = Session.getDefaultInstance(pros,auth);session.setDebug(true); //设置获取 debug 信息mimeMessage = new MimeMessage(session);}/*** 设置email系统参数* 接收一个map集合key为string类型,值为String* 发送邮件必须的步骤:2* @param map*/public void setPros(Map<String,String> map){pros = new Properties();for(Map.Entry<String,String> entry:map.entrySet()){pros.setProperty(entry.getKey(), entry.getValue());}}/*** 验证账号密码* 发送邮件必须的步骤* @author Administrator**/public class Email_Autherticator extends Authenticator{public PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication(username, password);}}/*** 设置发送邮件的基本参数(去除繁琐的邮件设置)* @param sub 设置邮件主题* @param text 设置邮件文本内容* @param rec 设置邮件接收人* @throws MessagingException* @throws UnsupportedEncodingException*/public void setDefaultMessagePros(String sub,String text,String rec) throws MessagingException, UnsupportedEncodingException{mimeMessage.setSubject(sub);mimeMessage.setText(text);mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec));mimeMessage.setSentDate(new Date());mimeMessage.setFrom(new InternetAddress(username,username));}/*** 设置主题* @param subject* @throws MessagingException */public void setSubject(String subject) throws MessagingException{mimeMessage.setSubject(subject);}/*** 设置日期* @param date* @throws MessagingException */public void setDate(Date date) throws MessagingException{mimeMessage.setSentDate(new Date());}/*** 设置邮件文本内容* @param text* @throws MessagingException*/public void setText(String text) throws MessagingException{mimeMessage.setText(text);}/*** 设置邮件头部* @param arg0* @param arg1* @throws MessagingException*/public void setHeader(String arg0,String arg1) throws MessagingException{mimeMessage.setHeader(arg0, arg1);}/*** 设置邮件接收人地址 <单人发送>* @param recipient* @throws MessagingException*/public void setRecipient(String recipient) throws MessagingException{mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));}/*** 设置邮件接收人地址 <多人发送>* @param list* @throws MessagingException * @throws AddressException */public String setRecipients(List<String> recs) throws AddressException, MessagingException{if(recs.isEmpty()){return "接收人地址为空!";}for(String str:recs){mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str));}return "加入接收人地址成功!";}/*** 设置邮件接收人地址 <多人发送>* @param StringBuffer<parms,parms2,parms.....>* @throws MessagingException * @throws AddressException */@SuppressWarnings("static-access")public String setRecipients(StringBuffer sb) throws AddressException, MessagingException{if(sb==null||"".equals(sb)){return "字符串数据为空!";}Address []address = new InternetAddress().parse(sb.toString());mimeMessage.addRecipients(Message.RecipientType.TO, address);return "收件人加入成功";}/*** 设置邮件发送人的名字* @param from* @throws UnsupportedEncodingException* @throws MessagingException*/public void setFrom(String from) throws UnsupportedEncodingException, MessagingException{mimeMessage.setFrom(new InternetAddress(username,from));}/*** 发送邮件<单人发送>* return 是否发送成功* @throws MessagingException */public String sendMessage() throws MessagingException{Transport.send(mimeMessage);return "success";}/*** 设置附件* @param file 发送文件的路径*/public void setMultipart(String file) throws MessagingException, IOException{if(multipart==null){multipart = new MimeMultipart();}multipart.addBodyPart(writeFiles(file));mimeMessage.setContent(multipart);}/*** 设置附件<添加多附件>* @param fileList<接收List集合>* @throws MessagingException* @throws IOException*/public void setMultiparts(List<String> fileList) throws MessagingException, IOException{if(multipart==null){multipart = new MimeMultipart();}for(String s:fileList){multipart.addBodyPart(writeFiles(s));}mimeMessage.setContent(multipart);}/*** 发送文本内容,设置编码方式* <方法与发送附件配套使用>* <发送普通的文本内容请使用setText()方法>* @param s* @param type* @throws MessagingException*/public void setContent(String s,String type) throws MessagingException{if(multipart==null){multipart = new MimeMultipart();}bodypart = new MimeBodyPart();bodypart.setContent(s, type);multipart.addBodyPart(bodypart);mimeMessage.setContent(multipart);mimeMessage.saveChanges();}/*** 读取附件* @param filePath* @return* @throws IOException* @throws MessagingException*/public BodyPart writeFiles(String filePath)throws IOException, MessagingException{File file = new File(filePath);if(!file.exists()){throw new IOException("文件不存在!请确定文件路径是否正确");}bodypart = new MimeBodyPart();DataSource dataSource = new FileDataSource(file);bodypart.setDataHandler(new DataHandler(dataSource));//文件名要加入编码,不然出现乱码bodypart.setFileName(MimeUtility.encodeText(file.getName()));return bodypart;}}

12345678910111213141516171819222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119111221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992000220320420520620720820921021121221321421521621721821921222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252

2、测试类:

package com.pleasurewithriding.assistantclass;import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.mail.MessagingException;public class TestSend{public static void main(String[] args) throws MessagingException, IOException{Map<String,String> map= new HashMap<String,String>();***SendMail mail = new SendMail("QQ号@","**你的授权码***");***map.put("mail.smtp.host", "");//暂时未成功,需要调试/*SendMail mail = new SendMail("14789****@","***miya");map.put("mail.smtp.host", "");*/map.put("mail.smtp.auth", "true");*****map.put("mail.smtp.socketFactory.class", ".ssl.SSLSocketFactory");map.put("mail.smtp.port", "465");map.put("mail.smtp.socketFactory.port", "465");*****mail.setPros(map);mail.initMessage();/** 添加收件人有三种方法:* 1,单人添加(单人发送)调用setRecipient(str);发送String类型* 2,多人添加(群发)调用setRecipients(list);发送list集合类型* 3,多人添加(群发)调用setRecipients(sb);发送StringBuffer类型*/List<String> list = new ArrayList<String>();list.add("****@");//list.add("***92@");list.add("****@");mail.setRecipients(list);/*String defaultStr = "283942930@,429353942@,2355663819@,381766286@;StringBuffer sb = new StringBuffer();sb.append(defaultStr);sb.append(",316121113@");mail.setRecipients(sb);*/mail.setSubject("测试邮箱");//mail.setText("谢谢合作");mail.setDate(new Date());mail.setFrom("MY");//mail.setMultipart("D:你你你.txt");mail.setContent("谢谢合作", "text/html; charset=UTF-8");/*List<String> fileList = new ArrayList<String>();fileList.add("D:1.jpg");fileList.add("D:activation.zip");fileList.add("D:dstz.sql");fileList.add("D:软件配置要求.doc");mail.setMultiparts(fileList);*/System.out.println(mail.sendMessage());}}

12345678910111213141516171819222324252627282930313233343536373839404142434445464748495051525354555657585960616263

代码中斜体加粗的地方就是我的改动:

1、构造函数初始化邮箱地址和密码的地方,前辈用的是163邮箱,我没去测试163邮箱了,直接用QQ邮箱了,但是要注意 QQ邮箱的密码不是你的 邮箱独立密码,当然更不是QQ密码,而是邮箱授权码,我之前在网上搜了很多文章,由于时间较早,都是用的邮箱独立密码(那时候腾讯还没有搞出授权码这个东西)测试成功,这个造成了我一时的困扰。不知道163邮箱是不是也出了授权码的概念,如果是,那么估计也是要用授权码代替密码吧,有兴趣的可以自己去测试。关于QQ邮箱授权码的获取,

进入QQ邮箱=》设置=》账户,在开启几个服务三方服务的时候,会要求获取授权码:

2、现在的QQ邮箱要求 使用 SSL 连接,当我把前辈的代码直接运行的时候,抛出了异常,叫什么 “530 Error: A secure connection is requiered(such as ssl)”,然后在网上找了别人的代码,发现加了这几句(我还没有去细究,等项目做完再说),

map.put(“mail.smtp.socketFactory.class”, “.ssl.SSLSocketFactory”);

map.put(“mail.smtp.port”, “465”);

map.put(“mail.smtp.socketFactory.port”, “465”);

3、如果你想看到 javamail 运行的 过程,加上 session.setDebug(true),我的源码里面已经加上了。

我的源码文件就不上了,因为所有代码都贴上来了,直接 copy 就可以的,好了,就说这么多,希望对跟我一样的小白有点帮助

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。