cy
2022-06-21 129904537f66509f97b285e7eb4f42b3dc349dd0
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
package cn.ksource.core.util;
 
import cn.ksource.web.Constants;
 
import java.util.Date;
import java.util.Properties;
 
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.AuthenticationFailedException;
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;
 
/**
 * 发送邮件测试通过
 * 
 * @author 安道彪
 */
 
public class EmailUtil {
 
    private static String fileName = Constants.APP_CONF_FILE;
    
    /**
     * 
     * @param emails
     * @param title
     * @param content
     * @param fileNames
     * @throws Exception
     */
    public static boolean sendEmail(String[] emails, String title,String content, String[] fileNames) throws Exception {
        String host = PropertyUtil.get(fileName, "host");
        String username = PropertyUtil.get(fileName, "username");
        String password = PropertyUtil.get(fileName, "password");
        String from = PropertyUtil.get(fileName, "from");
        boolean authentication = true;
 
        boolean flag = true;
        // 建立邮件会话
        Properties pro = new Properties();
        pro.put("mail.smtp.host", host);// 存储发送邮件的服务器
        MyEmailAuther myEmailAuther = null;
        if (authentication){ // 是否到服务器用户名和密码验证
            pro.put("mail.smtp.auth", "true");
            myEmailAuther = new MyEmailAuther(username, password);
        }
        else{
            pro.put("mail.smtp.auth", "false");
        }
 
        Session s = Session.getInstance(pro, (Authenticator) myEmailAuther); // 根据属性新建一个邮件会话
        // s.setDebug(true); //打开调试信息
        MimeMessage message = new MimeMessage(s); // 由邮件会话新建一个消息对象
        Transport transport = null;
        try {
            InternetAddress fromAddr = new InternetAddress(from); // 邮件发送地址
            message.setFrom(fromAddr); // 设置发送地址
 
            InternetAddress[] toAddr = new InternetAddress[emails.length];
            for (int i = 0; i < emails.length; i++) {
                toAddr[i] = new InternetAddress(emails[i]);
            }
            message.setRecipients(Message.RecipientType.TO, toAddr); // 设置接收地址
            BodyPart contentBodyPart = new MimeBodyPart();
            contentBodyPart.setContent(content, "text/html;charset=GBK");
            Multipart MimeMultipart = new MimeMultipart();
            MimeMultipart.addBodyPart(contentBodyPart);
            if(fileNames!=null){
                // 添加附件
                for (int i = 0; i < fileNames.length; i++) {
                    MimeBodyPart adjunct = new MimeBodyPart();
                    String filename = fileNames[i].split(",")[0]; // 选择出每一个附件名
                    String displayname = fileNames[i].split(",")[1];
                    FileDataSource fds = new FileDataSource(filename); // 得到数据源
                    adjunct.setDataHandler(new DataHandler(fds)); // 得到附件本身并至入BodyPart
                    adjunct.setFileName(MimeUtility.encodeText(displayname)); // 得到文件名同样至入BodyPart
                    MimeMultipart.addBodyPart(adjunct);
                }
            }
            message.setSubject(title); // 设置邮件标题
            message.setContent(MimeMultipart); // 设置邮件正文
            message.setSentDate(new Date()); // 设置发送日期
            message.saveChanges(); // 保存邮件更改信息
            System.out.println((authentication == false));
            if (authentication) {
                transport = s.getTransport("smtp");
                transport.connect(host, from, password);
                transport.sendMessage(message, message.getAllRecipients());
            } else {
                Transport.send(message);
            }
        } catch (AuthenticationFailedException e) {
            System.out.println("用户名或密码不正确!");
            e.printStackTrace();
            flag = false;
        } catch (AddressException e) {
            System.out.println("地址错误!");
            flag = false;
        } catch (MessagingException e) {
            System.out.println("消息发送错误,找不到服务器!");
            flag = false;
        }  catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }finally {
            try {
                transport.close();
            } catch (MessagingException e) {
                System.out.println("transport关闭错误!");
            }
        }
        return flag;
    }
    public static void main(String[] args) {
        String sendTo[] = { "964509855@qq.com"};
        try {
            EmailUtil.sendEmail(sendTo, "title", "content", null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
class MyEmailAuther extends Authenticator {
    private String username = null;
    private String pwd = null;
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public MyEmailAuther(String username, String pwd) {
        super();
        setUsername(username);
        setPwd(pwd);
 
    }
 
    public PasswordAuthentication getPasswordAuthentication() {
        System.out.println("username: " + username + "\npwd: " + pwd);
        return new PasswordAuthentication(username, pwd);
    }
}