admin管理员组

文章数量:1558997

maven 依赖

        
        <javaemail.version>1.4.5javaemail.version>
        <mail.version>1.4.1mail.version>
        
        <dependency>
        <groupid>javamailgroupid>
            <artifactid>javamailartifactid>
            <version>${javaemail.version}version>
        dependency>
        <dependency>
            <groupid>javax.mailgroupid>
            <artifactid>mailartifactid>
            <version>${mail.version}version>
        dependency>

email.properties

     #test emailwithfile
     mail.smtp.host=smtp.exmail.qq
     mail.smtp.port=465
     mail.smtp.protocol=smtp
     mail.sender.username=你的邮箱登录名
     mail.sender.password=你的邮箱密码

代码实现

  1. 未解决的问题:
    当发送多个人多邮件时,第一次发送采用ssl加密,但是第二次以后都不是采用ssl加密方式验证;
    我只创建了一个session,查看源代码发现,难道是每次发送邮件都会调用下面方法,session在第一次就消耗了?
 session s = (msg.session != null) ? msg.session session.getdefaultinstance(system.getproperties(), null);
  1. 代码改进
    查看源代码 如果不需要ssl加密可以采用transport.sendmessage(msg, addresses),因为transport.send(message,address[] address)调用了 transport.sendmessage(msg, addresses);
 session s = (msg.session != null) ? msg.session : session.getdefaultinstance(system.getproperties(), null);
    transport transport;
    if (dsize == 1) {
      transport = s.gettransport(addresses[0]);
      try {
        transport.connect();
        transport.sendmessage(msg, addresses);
      } finally {
        transport.close();
      }
      return;
    }

2.采用address[]会比采用internetaddress[]接收收件人发送多收件人邮件时更快,查看源代码发现
因为internetaddress是继承与address,
测试代码:同时向两个收件人发送两个附件信息:

long time1=system.currenttimemillis();
        boolean  issend=    sendemail.sendemail(subject, nickname, sendhtml, receiveuser, filepath);
        long time2=system.currenttimemillis();
        system.err.println("sendemail spend time:" (time2-time1));
对比结果采用address[]:
250 ok: queued as 
quit
221 bye
send success!
sendemail spend time:1520
对比结果采用internetaddress[]:
250 ok: queued as 
quit
221 bye
send success!
sendemail spend time:1210
3.经过实验发现当采用ssl验证时,邮件端口号为465,当不采用ssl验证时,端口号为25;
采用ssl验证:
debug: setdebug: javamail version 1.4.5
debug: getprovider() returning javax.mail.provider[transport,smtp,com.sun.mail.smtp.smtptransport,sun microsystems, inc]
debug smtp: useehlo true, useauth true
debug smtp: useehlo true, useauth true
debug smtp: trying to connect to host "smtp.exmail.qq", port 465, isssl true
220 smtp.qq esmtp qq mail server
debug smtp: connected to host "smtp.exmail.qq", port: 465
不采用ssl验证:
=09debug: setdebug: javamail version 1.4.5
debug: getprovider() returning javax.mail.provider[transport,smtp,com.sun.m=
ail.smtp.smtptransport,sun microsystems, inc]
debug smtp: useehlo true, useauth false
debug smtp: trying to connect to host "smtp.exmail.qq", port 25, isssl =
false
220 smtp.qq esmtp qq mail server
debug smtp: connected to host "smtp.exmail.qq", port: 25

附上源代码

package com.meyacom.tool;
import java.io.file;
import java.io.ioexception;
import java.io.inputstream;
import java.security.generalsecurityexception;
import java.util.arraylist;
import java.util.date;
import java.util.list;
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.internetaddress;
import javax.mail.internet.mimebodypart;
import javax.mail.internet.mimemessage;
import javax.mail.internet.mimemultipart;
import javax.mail.internet.mimeutility;
import org.apachemons.lang.stringutils;
import org.apache.log4j.logger;
import com.sun.mail.util.mailsslsocketfactory;
/**
 * title: fileemaliutil
 * 

* description:发送带附件的邮件(多收件人多附件) *

* j9九游会老哥俱乐部交流区 copyright: j9九游会老哥俱乐部交流区 copyright (c) 2016 *

* company: *

* * @author zhoulin.zhu *

* 2016年8月25日 */ public class sendemaliutil { protected logger logger = logger.getlogger(this.getclass()); private mimemessage message; private string mailhost = ""; private string mailport = ""; private string mailprotocol = ""; private string sender_username = ""; private string sender_password = ""; private properties properties = new properties(); /* * 初始化方法 */ public sendemaliutil(boolean debug) { inputstream in = classloader .getsystemresourceasstream("email.properties"); try { properties.load(in); this.mailhost = properties.getproperty("mail.smtp.host"); this.mailport = properties.getproperty("mail.smtp.port"); this.mailprotocol = properties.getproperty("mail.smtp.protocol"); this.sender_username = properties .getproperty("mail.sender.username"); this.sender_password = properties .getproperty("mail.sender.password"); } catch (ioexception e) { system.out.println("读取默认参数文件异常,请重试!"); } } /** * 用户名密码验证,需要实现抽象类authenticator的抽象方法passwordauthentication, * smtp验证类(内部类),继承javax.mail.authenticator */ class myauthenricator extends authenticator { string username = null; string password = null; public myauthenricator(string username, string password) { this.username = username; this.password = password; } @override protected passwordauthentication getpasswordauthentication() { return new passwordauthentication(username, password); } } /** * 指定发送邮件 * * @param subject * 邮件主题 * @param sendhtml * 邮件内容 * @param sender_nickname * 发送邮件人地址 * @param receiveuser * 收件人列表,以","分割 * @param filepath * 附件列表 */ public boolean sendemail(string subject, string sender_nickname, string sendhtml, string receiveuser, list filepath) { properties prop = new properties(); // 协议 prop.setproperty("mail.transport.protocol", mailprotocol); // 服务器 prop.setproperty("mail.smtp.host", mailhost); // 端口 prop.setproperty("mail.smtp.port", mailport); // 使用smtp身份验证 prop.setproperty("mail.smtp.auth", "true"); // 使用ssl,企业邮箱必需! // 开启安全协议 mailsslsocketfactory sf = null; try { sf = new mailsslsocketfactory(); sf.settrustallhosts(true); } catch (generalsecurityexception e1) { system.out.println("开启ssl加密异常!"); e1.printstacktrace(); return false; } prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketfactory", sf); session session = session.getdefaultinstance(prop, new myauthenricator( sender_username, sender_password)); session.setdebug(true);// 开启debug模式,在控制台中或日志中有日志信息显示,也就是可以从控制台中看一下服务器的响应信息; message = new mimemessage(session); try { internetaddress from; if (stringutils.isnotblank(sender_nickname)) { // 发件人,昵称 from = new internetaddress( mimeutility.encodeword(sender_nickname) "<" sender_username ">"); } else { // 发件人 from = new internetaddress( mimeutility.encodeword(sender_nickname)); } message.setfrom(from); // 创建收件人列表 if (stringutils.isnotblank(receiveuser)) { // 替换收件人的分隔符(防止中文下产生无法分割成收件人数组的','替换成',') string rescivers = receiveuser.replaceall(",", ","); string[] arr = rescivers.split(","); if (arr.length > 0) { // 收件人 //采用address【】比internetaddress发送邮件速度更快 因为internetaddress是继承与address, address[] address=new address[arr.length]; //internetaddress[] address = new internetaddress[arr.length]; for (int i = 0; i < arr.length; i ) { address[i] = new internetaddress(arr[i]); } message.setrecipients(message.recipienttype.to, address); // 发送时间 message.setsentdate(new date()); // 邮件主题 message.setsubject(subject); // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 multipart multipart = new mimemultipart(); // 添加邮件正文 bodypart contentpart = new mimebodypart(); contentpart.setcontent(sendhtml, "text/html;charset=utf-8"); multipart.addbodypart(contentpart); // 附件操作 if (filepath != null && filepath.size() > 0) { for (string filename : filepath) { bodypart attachmentbodypart = new mimebodypart(); datasource source = new filedatasource(filename); attachmentbodypart.setdatahandler(new datahandler( source)); // mimeutility.encodeword可以避免文件名乱码 attachmentbodypart.setfilename(mimeutility .encodeword(source.getname())); multipart.addbodypart(attachmentbodypart); } // 移走集合中的所有元素 filepath.clear(); } // 将multipart对象放到message中 message.setcontent(multipart); // 保存邮件 message.savechanges(); // 不采用ssl加密发送 // transport = session.gettransport("smtp"); // smtp验证,就是你用来发邮件的邮箱用户名密码 // transport.connect(mailhost, sender_username, // sender_password); // 发送 // transport.sendmessage(message, // message.getallrecipients()); // 发送 transport.send(message,address); system.out.println("send success!"); } } return true; } catch (exception e) { system.out.println("message异常!"); e.printstacktrace(); return false; } } public static void main(string[] args) { string subject = "测试"; string nickname = "风中思絮"; string sendhtml = "

由于下雨,周末不加班!

"
; string receiveuser = "xxx@meyacom,xxx@qq"; // string receiveuser = "xxx@qq"; list filepath = new arraylist(); // filepath.add("d:\\javastudy\\bpm学习\\svn地址.txt"); filepath.add("d:\\javastudy\\学习进度\\学习目标及目标.txt"); // filepath.add("d:\\javastudy\\bpm学习\\bpm配置文档(1).docx"); filepath.add("d:\\javastudy\\bpm学习\\oa\\任务分配.png"); // filepath.add("d:\\javastudy\\微信支付.rar"); sendemaliutil sendemail = new sendemaliutil(true); long time1=system.currenttimemillis(); boolean issend= sendemail.sendemail(subject, nickname, sendhtml, receiveuser, filepath); long time2=system.currenttimemillis(); system.err.println("sendemail spend time:" (time2-time1)); } }

本文标签: 邮箱腾讯发送邮件企业邮箱