1
/** *//**
2
* 該類演示了Java Mail的應用
3
* 版權 本文版權屬Java天下
4
* @author ljfan
5
* @version 2.0, Created on 2005/08/10
6
*
7
*/
8
9
package cn.javatx.util;
10
11
import java.io.FileInputStream;
12
import java.text.SimpleDateFormat;
13
import java.util.Collection;
14
import java.util.Collections;
15
import java.util.Date;
16
import java.util.Properties;
17
import java.util.concurrent.ArrayBlockingQueue;
18
import java.util.concurrent.ThreadPoolExecutor;
19
import java.util.concurrent.TimeUnit;
20
21
import javax.mail.Address;
22
import javax.mail.Message;
23
import javax.mail.MessagingException;
24
import javax.mail.Part;
25
import javax.mail.SendFailedException;
26
import javax.mail.Session;
27
import javax.mail.Transport;
28
import javax.mail.URLName;
29
import javax.mail.internet.AddressException;
30
import javax.mail.internet.InternetAddress;
31
import javax.mail.internet.MimeBodyPart;
32
import javax.mail.internet.MimeMessage;
33
import javax.mail.internet.MimeMultipart;
34
import javax.mail.internet.MimeUtility;
35
36
public class Mail
{
37
38
private String host;
39
40
private int port;
41
42
private String username;
43
44
private String password;
45
46
ThreadPoolExecutor executor = null;
47
48
private static Mail mail = new Mail();
49
50
public static Mail getInstance()
{
51
return mail;
52
}
53
54
private Mail()
{
55
try
{
56
Properties prop = new Properties();
57
FileInputStream fis = new FileInputStream("H:\\Tomcat5\\webapps\\ROOT\\WEB-INF\\classes\\mail.properties");
58
prop.load(fis);
59
60
this.host = prop.getProperty("mail.smtp.host");
61
this.port = Integer.parseInt(prop.getProperty("mail.smtp.port"));
62
this.username = prop.getProperty("mail.smtp.username");
63
this.password = prop.getProperty("mail.smtp.password");
64
65
System.out.println("host:"+host);
66
System.out.println("port:"+port);
67
68
} catch (Exception e)
{
69
System.out.println(e.getMessage());
70
}
71
72
executor = new ThreadPoolExecutor(1, Integer.MAX_VALUE, 60,
73
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));
74
}
75
76
private Session session = null;
77
78
/** *//**
79
* Creates a Javamail session.
80
*/
81
private synchronized void createSession()
{
82
if (host == null)
{
83
throw new IllegalArgumentException("Host cannot be null.");
84
}
85
86
Properties mailProps = new Properties();
87
mailProps.setProperty("mail.smtp.host", host);
88
mailProps.setProperty("mail.smtp.port", String.valueOf(port));
89
mailProps.setProperty("mail.smtp.sendpartial", "true");
90
if (username != null)
{
91
mailProps.put("mail.smtp.auth", "true");
92
}
93
session = Session.getInstance(mailProps, null);
94
}
95
96
public MimeMessage createMimeMessage()
{
97
if (session == null)
{
98
createSession();
99
}
100
return new MimeMessage(session);
101
}
102
103
/** *//**
104
* 發送郵件
105
*
106
* @param fromName
107
* 發件人姓名
108
* @param fromEmail
109
* 發件人地址
110
* @param ToEmail
111
* 收件人地址
112
* @param CcEmail
113
* 抄送人地址
114
* @param subject
115
* 郵件主題
116
* @param textBody
117
* 郵件內容
118
* @param htmlBody
119
* 郵件內容(html形式)
120
*/
121
public void sendMessage(String fromName, String fromEmail, String ToEmail,
122
String CcEmail, String subject, String textBody, String htmlBody)
{
123
try
{
124
String encoding = MimeUtility.mimeCharset("gb2312");
125
MimeMessage message = createMimeMessage();
126
127
String sTo[] = ToEmail.split(",");
128
String sCc[] = CcEmail.split(",");
129
130
//收件人地址
131
Address to[] = new Address[sTo.length];
132
for (int i = 0; i < sTo.length; i++)
{
133
to[i] = new InternetAddress(sTo[i], "", encoding);
134
}
135
136
//抄送人地址
137
Address cc[] = new Address[sCc.length];
138
for (int i = 0; i < sTo.length; i++)
{
139
cc[i] = new InternetAddress(sCc[i], "", encoding);
140
}
141
142
Address from = null;
143
144
if (fromName != null)
{
145
from = new InternetAddress(fromEmail, fromName, encoding);
146
} else
{
147
from = new InternetAddress(fromEmail, "", encoding);
148
}
149
150
SimpleDateFormat format = new SimpleDateFormat(
151
"EEE, dd MMM yyyy HH:mm:ss Z", java.util.Locale.US);
152
153
message.setHeader("Date", format.format(new Date()));
154
message.setHeader("Content-Transfer-Encoding", "8bit");
155
message.setRecipients(Message.RecipientType.TO, to);
156
if (!(CcEmail.equals("")) || (CcEmail == null))
{
157
message.setRecipients(Message.RecipientType.CC, cc);
158
}
159
message.setFrom(from);
160
message.setSubject(subject, encoding);
161
// Create HTML, plain-text, or combination message
162
if (textBody != null && htmlBody != null)
{
163
MimeMultipart content = new MimeMultipart("alternative");
164
// Plain-text
165
MimeBodyPart text = new MimeBodyPart();
166
text.setText(textBody, encoding);
167
text.setDisposition(Part.INLINE);
168
content.addBodyPart(text);
169
// HTML
170
MimeBodyPart html = new MimeBodyPart();
171
html.setContent(htmlBody, "text/html");
172
html.setDisposition(Part.INLINE);
173
content.addBodyPart(html);
174
// Add multipart to message.
175
message.setContent(content);
176
message.setDisposition(Part.INLINE);
177
addToTask(message);
178
} else if (textBody != null)
{
179
MimeBodyPart bPart = new MimeBodyPart();
180
bPart.setText(textBody, encoding);
181
bPart.setDisposition(Part.INLINE);
182
MimeMultipart mPart = new MimeMultipart();
183
mPart.addBodyPart(bPart);
184
message.setContent(mPart);
185
message.setDisposition(Part.INLINE);
186
addToTask(message);
187
} else if (htmlBody != null)
{
188
MimeBodyPart bPart = new MimeBodyPart();
189
bPart.setContent(htmlBody, "text/html");
190
bPart.setDisposition(Part.INLINE);
191
MimeMultipart mPart = new MimeMultipart();
192
mPart.addBodyPart(bPart);
193
message.setContent(mPart);
194
message.setDisposition(Part.INLINE);
195
addToTask(message);
196
}
197
} catch (Exception e)
{
198
System.out.println(e.getMessage());
199
}
200
}
201
202
private void addToTask(MimeMessage message)
{
203
if (message != null)
{
204
sendMessages(Collections.singletonList(message));
205
} else
{
206
System.out.println("Cannot add null email message to queue.");
207
}
208
209
}
210
211
public void sendMessages(Collection<MimeMessage> messages)
{
212
if (messages.size() == 0)
{
213
return;
214
}
215
executor.execute(new EmailTask(messages));
216
}
217
218
/** *//**
219
* Task to send one or more emails via the SMTP server.
220
*/
221
private class EmailTask implements Runnable
{
222
223
private Collection<MimeMessage> messages;
224
225
public EmailTask(Collection<MimeMessage> messages)
{
226
this.messages = messages;
227
}
228
229
public void run()
{
230
try
{
231
sendMessages();
232
} catch (MessagingException me)
{
233
System.out.println(me.getMessage());
234
}
235
}
236
237
public void sendMessages() throws MessagingException
{
238
Transport transport = null;
239
try
{
240
URLName url = new URLName("smtp", host, port, "", username,
241
password);
242
transport = new com.sun.mail.smtp.SMTPTransport(session, url);
243
transport.connect(host, port, username, password);
244
//System.out.println(messages.size());
245
for (MimeMessage message : messages)
{
246
try
{
247
transport.sendMessage(message, message
248
.getRecipients(MimeMessage.RecipientType.TO));
249
} catch (AddressException ae)
{
250
System.out.println(ae.getMessage());
251
} catch (SendFailedException sfe)
{
252
System.out.println(sfe.getMessage());
253
}
254
}
255
} finally
{
256
if (transport != null)
{
257
try
{
258
transport.close();
259
} catch (MessagingException e)
{ /**//* ignore */
260
}
261
}
262
}
263
}
264
}
265
}
266


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

186

187



188

189

190

191

192

193

194

195

196

197



198

199

200

201

202



203



204

205



206

207

208

209

210

211



212



213

214

215

216

217

218


219

220

221



222

223

224

225



226

227

228

229



230



231

232



233

234

235

236

237



238

239



240

241

242

243

244

245



246



247

248

249



250

251



252

253

254

255



256



257



258

259



260

261

262

263

264

265

266

Java天下社區
http://www.javatx.cn
歡迎大家上來交流Java技術。