EmailUtil工具类 - 军军小站|张军博客

EmailUtil工具类

张军 5735 0

所有工具类

本文章向大家介绍EmailUtil,主要包括EmailUtil使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package zj.email.util;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
 
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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.apache.log4j.Logger;
 
import zj.check.util.CheckUtil;
import zj.common.exception.ServiceException;
import zj.email.bean.EmailDto;
import zj.java.util.JavaUtil;
 
/**
 * 概况 :EmailUtil工具类<br>
 
 * @version 1.00 (2011.12.02)
 * @author SHNKCS 张军 {@link <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a>&nbsp;&nbsp;&nbsp;&nbsp;<a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>} <br>
 */
public class EmailUtil {
    private static Logger logger = Logger.getLogger(EmailUtil.class);
 
    /**
     * 发送邮件
     
     * @param dto
     */
    public static boolean sendEmail(EmailDto dto) {
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", dto.getMailSmtpHost());
            props.put("mail.smtp.auth""true");
            // 使用 STARTTLS安全连接:
            // props.setProperty("mail.smtp.port", "465");
            // props.setProperty("mail.smtp.starttls.enable", "true");
            // props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            // props.setProperty("mail.smtp.socketFactory.fallback", "false");
            if (dto.getPropertiesMap() != null && dto.getPropertiesMap().size() > 0) {
                props.putAll(dto.getPropertiesMap());
            }
            // 邮件会话类Session,跟httpSession类似。传入属性设置properties和授权验证对象
            Session session = null;
            // 无授权验证
            session = Session.getInstance(props);
            // 授权验证
            // SmtpAuth auth = new SmtpAuth();
            // auth.setUser(dto.getUser());
            // auth.setPassword(dto.getPassword());
            // session = Session.getInstance(props, auth);
 
            session.setDebug(dto.isDebug());
            // 由邮件会话新建一个消息对象
            MimeMessage message = new MimeMessage(session);
            InternetAddress from = new InternetAddress(dto.getFromAddress());
            // 设置发信人
            message.setFrom(from);
            // 设置收信人
            if (CheckUtil.isNotNull(dto.getToAddresses())) {
                String[] sary = JavaUtil.split(dto.getToAddresses(), ";");
                List<String> emails = new ArrayList<String>();
                for (int i = 0; i < sary.length; i++) {
                    if (CheckUtil.isEmail(sary[i])) {
                        emails.add(sary[i]);
                    else {
                        logger.warn("无效的收件人邮件地址:" + sary[i]);
                    }
                }
                if (emails.size() > 0) {
                    Address[] addressAry = new InternetAddress[emails.size()];
                    for (int i = 0; i < emails.size(); i++) {
                        String email = emails.get(i);
                        addressAry[i] = new InternetAddress(email);
                    }
                    message.setRecipients(Message.RecipientType.TO, addressAry);
                else {
                    throw new ServiceException("验证所有收件人失败,收件人至少有一个人");
                }
            else {
                throw new ServiceException("收件人至少有一个人");
            }
            // 设置抄送人
            if (CheckUtil.isNotNull(dto.getCcAddresses())) {
                String[] sary = JavaUtil.split(dto.getCcAddresses(), ";");
                List<String> emails = new ArrayList<String>();
                for (int i = 0; i < sary.length; i++) {
                    if (CheckUtil.isEmail(sary[i])) {
                        emails.add(sary[i]);
                    else {
                        logger.warn("无效的抄送人邮件地址:" + sary[i]);
                    }
                }
                if (emails.size() > 0) {
                    Address[] addressAry = new InternetAddress[emails.size()];
                    for (int i = 0; i < emails.size(); i++) {
                        String email = emails.get(i);
                        addressAry[i] = new InternetAddress(email);
                    }
                    message.setRecipients(Message.RecipientType.CC, addressAry);
                }
            }
            // 设置密送人
            if (CheckUtil.isNotNull(dto.getBccAddresses())) {
                String[] sary = JavaUtil.split(dto.getBccAddresses(), ";");
                List<String> emails = new ArrayList<String>();
                for (int i = 0; i < sary.length; i++) {
                    if (CheckUtil.isEmail(sary[i])) {
                        emails.add(sary[i]);
                    else {
                        logger.warn("无效的密送人邮件地址:" + sary[i]);
                    }
                }
                if (emails.size() > 0) {
                    Address[] addressAry = new InternetAddress[emails.size()];
                    for (int i = 0; i < emails.size(); i++) {
                        String email = emails.get(i);
                        addressAry[i] = new InternetAddress(email);
                    }
                    message.setRecipients(Message.RecipientType.BCC, addressAry);
                }
            }
            // 设置主题
            message.setSubject(dto.getSubject());
            // 设置发信时间
            message.setSentDate(new Date());
            // 发送邮件
            Multipart mm = new MimeMultipart();
            if (dto.getContentObj() == null) {
                dto.setContentObj("");
            }
            BodyPart mdpContent = new MimeBodyPart();
            // 添加内容
            mdpContent.setContent(dto.getContentObj(), dto.getContentType());
            mm.addBodyPart(mdpContent);
            // 添加附件
            if (CheckUtil.isNotNull(dto.getFileDataSources())) {
                String[] sary = JavaUtil.split(dto.getFileDataSources(), ";");
                String[] saryName = JavaUtil.split(dto.getFileDataSourcesName(), ";");
                for (int i = 0; i < sary.length; i++) {
                    FileDataSource fdsFile = new FileDataSource(sary[i]);
                    DataHandler dh = new DataHandler(fdsFile);
                    BodyPart mdpAttachment = new MimeBodyPart();
                    String fileName = null;
                    if (saryName.length > i) {
                        fileName = saryName[i];
                    }
                    if (CheckUtil.isNull(fileName)) {
                        fileName = fdsFile.getName();
                    }
                    mdpAttachment.setFileName(MimeUtility.encodeWord(fileName));
                    mdpAttachment.setDataHandler(dh);
                    mm.addBodyPart(mdpAttachment);
                }
            }
            message.setContent(mm);
            // 保存改变
            message.saveChanges();
            // ****************************************************//
            Transport transport = session.getTransport(dto.getProtocol());
            // 以smtp方式登录邮箱,第一个参数是发送邮件用的邮件服务器SMTP地址,第二个参数为用户名,第三个参数密码
            transport.connect(dto.getMailSmtpHost(), dto.getUser(), dto.getPassword());
            // 发送邮件,其中第二个参数是所有已设好的收件人地址
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            logger.info("发送邮件成功");
            return true;
        catch (Exception e) {
            throw new ServiceException(e);
        }
    }
}

email工具类参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package zj.email.bean;
 
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
 
import lombok.Data;
import zj.check.util.CheckUtil;
import zj.java.util.JavaUtil;
 
/**
 * email工具类参数<br>
 
 * @version 1.00 (2011/11/08)
 * @author 张军 {@link  <a target=_blank href="http://www.zhangjunbk.com">张军个人网站</a>&nbsp;&nbsp;&nbsp;&nbsp;<a target=_blank href="http://user.qzone.qq.com/360901061/">张军QQ空间</a>}
 */
@Data
public class EmailDto implements Serializable {
 
    private static final long serialVersionUID = 1L;
 
    /**
     * 发件人使用发邮件的电子信箱服务器,默认smtp.126.com
     */
    private String mailSmtpHost;
    /**
     * 是否调试
     */
    private boolean debug;
    /**
     * 发送人邮箱地址
     */
    private String fromAddress;
    /**
     * 收件人邮箱地址(多个以;号隔开)
     */
    private String toAddresses;
    /**
     * 密送人邮箱地址(多个以;号隔开)
     */
    private String bccAddresses;
    /**
     * 抄送人邮箱地址(多个以;号隔开)
     */
    private String ccAddresses;
    /**
     * 设置主题
     */
    private String subject;
    /**
     * 发送主体内容
     */
    private Object contentObj;
    /**
     * 编码,默认text/html;charset=UTF-8
     */
    private String contentType = "text/html;charset=UTF-8";
    /**
     * 附件地址
     */
    private String fileDataSources;
    /**
     * 附件地址名
     */
    private String fileDataSourcesName;
    /**
     * 协议,默认smtp
     */
    private String protocol = "smtp";
    /**
     * 发送邮件用户名
     */
    private String user;
    /**
     * 发送邮件密码
     */
    private String password;
    // 属性设置
    private Map<String, Object> propertiesMap = new HashMap<String, Object>();
    /**
     * 是否465端口发送
     */
    private boolean send465Port;
 
    /**
     * 自动设置用户名
     */
    public void autoSetUser() {
        if (CheckUtil.isNull(user)) {
            // 设置用户名
            String[] userAry = JavaUtil.split(this.fromAddress, "@");
            if (userAry.length > 0) {
                user = userAry[0];
            }
        }
    }
 
    /**
     * 改成465端口发送
     */
    private void send465Port() {
        if (isSend465Port()) {
            propertiesMap.put("mail.smtp.port""465");
            propertiesMap.put("mail.smtp.starttls.enable""true");
            propertiesMap.put("mail.smtp.socketFactory.class""javax.net.ssl.SSLSocketFactory");
            propertiesMap.put("mail.smtp.socketFactory.fallback""false");
        }
    }
 
    /**
     * 自动设置服务器
     */
    public void autoSetMailSmtpHost() {
        if (CheckUtil.isNull(mailSmtpHost)) {
            String[] userAry = JavaUtil.split(this.fromAddress, "@");
            if (userAry.length > 1) {
                String hosts[] = JavaUtil.split(userAry[1], ".");
                if (hosts.length > 0) {
                    String host = hosts[0];
                    if ("qq".equalsIgnoreCase(host) || "allianity".equalsIgnoreCase(host)) {
                        mailSmtpHost = "smtp.qq.com";
                    else if ("yahoo".equalsIgnoreCase(host)) {
                        mailSmtpHost = "smtp.mail.yahoo.com.cn";
                    else if ("163".equalsIgnoreCase(host)) {
                        mailSmtpHost = "smtp.163.com";
                    else if ("126".equalsIgnoreCase(host)) {
                        mailSmtpHost = "smtp.126.com";
                    else if ("notice".equalsIgnoreCase(host)) {
                        mailSmtpHost = "smtpdm.aliyun.com";
                    else {
                        mailSmtpHost = "smtp.126.com";
                    }
                    // 设置发送邮件端口号
                    send465Port();
                }
            }
        }
    }
}



更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论