轉自:http://www.aygfsteel.com/fastzch/archive/2007/12/03/164912.html
1,讀入圖片的方式:
發現網上講的很多讀取圖片的方式都不對,按下面提供的這個方法來讀取,保證成功。
1
private byte[] getImageBytes(String file)
{
2
byte[] myData = null;
3
InputStream input = getClass().getClassLoader().getResourceAsStream(
4
file);
5
try
{
6
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
7
int ch = 0;
8
while ((ch = input.read()) != -1)
{
9
byteArray.write(ch);
10
}
11
// System.out.println(byteArray.size());
12
myData = byteArray.toByteArray();
13
// System.out.println(myData.length);
14
} catch (Exception e)
{
15
e.printStackTrace();
16
}
17
return myData;
18
}
2,發送郵件的“機關”
1
MimeMessage msg = new MimeMessage(mailSession);
2
msg.setFrom(new InternetAddress(this.getSenderAddress()));
3
msg.setSubject(this.getTitle());
4
msg.setSentDate(new Date());
5
Address[] adds = InternetAddress.parse(getToAddress());
6
msg.addRecipients(javax.mail.Message.RecipientType.TO, adds);
7
// 新建一個MimeMultipart對象用來存放BodyPart對象(事實上可以存放多個)
8
MimeMultipart mm = new MimeMultipart("related");
9
// 新建一個存放信件內容的BodyPart對象
10
BodyPart mdp = new MimeBodyPart();
11
// 給BodyPart對象設置內容和格式/編碼方式
12
mdp.setContent(this.getContent(), "text/html;charset=utf-8");
13
// 這句很重要,千萬不要忘了
14
mm.addBodyPart(mdp);
15
16
// ---------圖片處理開始?。。。。。。。。。。。。。。。?/span>
17
mdp = new MimeBodyPart();
18
byte bbb[] = new byte[1024 * 10];
19
this.getClass().getClassLoader().getResourceAsStream("notice.jpg")
20
.read(bbb);
21
DataHandler dh = new DataHandler(new ByteArrayDataSource(this
22
.getImageBytes("notice.jpg"), "application/octet-stream"));
23
mdp.setDataHandler(dh);
24
// 加上這句將作為附件發送,否則將作為信件的文本內容
25
mdp.setFileName("1.jpg");
26
mdp.setHeader("content-id", "<IMG1>");
27
// 將含有附件的BodyPart加入到MimeMultipart對象中
28
mm.addBodyPart(mdp);
29
// ---------圖片處理結束?。。。。。。。。。。。。。。。?br />
30
31
// 把mm作為消息對象的內容
32
msg.setContent(mm);
仔細看代碼中的注釋吧,相信大有幫助。
3,一個實際應用的完整代碼
要求根據一個格式文件和模版,發一封漂亮的郵件,所以需要用到HTML格式來發送郵件。不多說了,看代碼吧!


1
import java.io.ByteArrayOutputStream;
2
import java.io.File;
3
import java.io.FileReader;
4
import java.io.IOException;
5
import java.io.InputStream;
6
import java.util.Date;
7
import java.util.HashMap;
8
import java.util.Map;
9
import java.util.Properties;
10
11
import javax.activation.DataHandler;
12
import javax.mail.Address;
13
import javax.mail.BodyPart;
14
import javax.mail.internet.InternetAddress;
15
import javax.mail.internet.MimeBodyPart;
16
import javax.mail.internet.MimeMessage;
17
import javax.mail.internet.MimeMultipart;
18
import javax.mail.util.ByteArrayDataSource;
19
20
/** *//**
21
*
22
* @author robin
23
* @version $Revision: 1.4 $
24
*/
25
public class SendMailUtil
{
26
27
/** *//**
28
* Field mailServerAddress.
29
*/
30
private String mailServerAddress;
31
32
/** *//**
33
* Field user.
34
*/
35
private String user;
36
37
/** *//**
38
* Field password.
39
*/
40
private String password;
41
42
/** *//**
43
* Field toAddress.
44
*/
45
private String toAddress;
46
47
/** *//**
48
* Field ccAddress.
49
*/
50
private String ccAddress;
51
52
/** *//**
53
* Field title.
54
*/
55
private String title;
56
57
/** *//**
58
* Field content.
59
*/
60
private String content;
61
62
/** *//**
63
* Field isHtml.
64
*/
65
private boolean isHtml = true;
66
67
/** *//**
68
* Field attachmentFiles.
69
*/
70
private Map attachmentFiles = null;
71
72
/** *//**
73
* Field senereAddress.
74
*/
75
private String senderAddress;
76
77
private byte[] getImageBytes(String file)
{
78
byte[] myData = null;
79
InputStream input = getClass().getClassLoader().getResourceAsStream(
80
file);
81
try
{
82
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
83
int ch = 0;
84
while ((ch = input.read()) != -1)
{
85
byteArray.write(ch);
86
}
87
// System.out.println(byteArray.size());
88
myData = byteArray.toByteArray();
89
// System.out.println(myData.length);
90
} catch (Exception e)
{
91
e.printStackTrace();
92
}
93
return myData;
94
}
95
96
public void sendMail() throws Exception
{
97
Properties pos = new Properties();
98
pos.put("mail.smtp.host", "10.5.1.1");
99
javax.mail.Session mailSession = javax.mail.Session.getInstance(pos,
100
null);
101
MimeMessage msg = new MimeMessage(mailSession);
102
msg.setFrom(new InternetAddress(this.getSenderAddress()));
103
msg.setSubject(this.getTitle());
104
msg.setSentDate(new Date());
105
Address[] adds = InternetAddress.parse(getToAddress());
106
msg.addRecipients(javax.mail.Message.RecipientType.TO, adds);
107
// 新建一個MimeMultipart對象用來存放BodyPart對象(事實上可以存放多個)
108
MimeMultipart mm = new MimeMultipart("related");
109
// 新建一個存放信件內容的BodyPart對象
110
BodyPart mdp = new MimeBodyPart();
111
// 給BodyPart對象設置內容和格式/編碼方式
112
mdp.setContent(this.getContent(), "text/html;charset=utf-8");
113
// 這句很重要,千萬不要忘了
114
mm.addBodyPart(mdp);
115
116
// ---------圖片處理開始?。。。。。。。。。。。。。。?!
117
mdp = new MimeBodyPart();
118
byte bbb[] = new byte[1024 * 10];
119
this.getClass().getClassLoader().getResourceAsStream("notice.jpg")
120
.read(bbb);
121
DataHandler dh = new DataHandler(new ByteArrayDataSource(this
122
.getImageBytes("notice.jpg"), "application/octet-stream"));
123
mdp.setDataHandler(dh);
124
// 加上這句將作為附件發送,否則將作為信件的文本內容
125
mdp.setFileName("1.jpg");
126
mdp.setHeader("content-id", "<IMG1>");
127
// 將含有附件的BodyPart加入到MimeMultipart對象中
128
mm.addBodyPart(mdp);
129
// ---------圖片處理結束?。。。。。。。。。。。。。。?!
130
131
// 把mm作為消息對象的內容
132
msg.setContent(mm);
133
msg.saveChanges();
134
javax.mail.Transport transport = mailSession.getTransport("smtp");
135
transport.connect();
136
transport.sendMessage(msg, msg.getAllRecipients());
137
transport.close();
138
139
}
140
141
/** *//**
142
* Method getCcAddress.
143
*
144
* @return String
145
*/
146
public String getCcAddress()
{
147
return ccAddress;
148
}
149
150
/** *//**
151
* Method getContent.
152
*
153
* @return String
154
*/
155
public String getContent()
{
156
if (content == null)
{
157
return "";
158
} else
{
159
return content;
160
}
161
}
162
163
/** *//**
164
* Method getMailServerAddress.
165
*
166
* @return String
167
*/
168
public String getMailServerAddress()
{
169
return "10.5.1.1";
170
}
171
172
/** *//**
173
* Method getSenderId.
174
*
175
* @return String
176
*/
177
public String getUser()
{
178
if (user == null || user.equals(""))
{
179
user = "";
180
}
181
return user;
182
}
183
184
/** *//**
185
* Method getPassword.
186
*
187
* @return String
188
*/
189
public String getPassword()
{
190
if (password == null || password.equals(""))
{
191
password = "";
192
}
193
return password;
194
}
195
196
/** *//**
197
* Method getTitle.
198
*
199
* @return String
200
*/
201
public String getTitle()
{
202
if (title == null)
{
203
return "";
204
} else
{
205
return title;
206
}
207
}
208
209
/** *//**
210
* Method getToAddress.
211
*
212
* @return String
213
*/
214
public String getToAddress()
{
215
return toAddress;
216
}
217
218
/** *//**
219
* Method isHtml.
220
*
221
* @return boolean
222
*/
223
public boolean isHtml()
{
224
return isHtml;
225
}
226
227
/** *//**
228
* Method setCcAddress.
229
*
230
* @param ccAddress
231
* String
232
*/
233
public void setCcAddress(String ccAddress)
{
234
this.ccAddress = ccAddress;
235
}
236
237
/** *//**
238
* Method setContent.
239
*
240
* @param content
241
* String
242
*/
243
public void setContent(String content)
{
244
this.content = content;
245
}
246
247
/** *//**
248
* Method setMailServerAddress.
249
*
250
* @param mailServerAddress
251
* String
252
*/
253
public void setMailServerAddress(String mailServerAddress)
{
254
this.mailServerAddress = mailServerAddress;
255
}
256
257
/** *//**
258
* Method setUser.
259
*
260
* @param user
261
* String
262
*/
263
public void setUser(String user)
{
264
this.user = user;
265
}
266
267
/** *//**
268
* Method setSenderPassword.
269
*
270
* @param password
271
* String
272
*/
273
public void setPassword(String password)
{
274
this.password = password;
275
}
276
277
/** *//**
278
* Method setTitle.
279
*
280
* @param title
281
* String
282
*/
283
public void setTitle(String title)
{
284
this.title = title;
285
}
286
287
/** *//**
288
* Method setToAddress.
289
*
290
* @param toAddress
291
* String
292
*/
293
public void setToAddress(String toAddress)
{
294
this.toAddress = toAddress;
295
}
296
297
/** *//**
298
* Method setIsHtml.
299
*
300
* @param isHtml
301
* boolean
302
*/
303
public void setIsHtml(boolean isHtml)
{
304
this.isHtml = isHtml;
305
}
306
307
/** *//**
308
* Method setAttachmentFiles.
309
*
310
* @param attachmentFiles
311
* Map
312
*/
313
public void setAttachmentFiles(Map attachmentFiles)
{
314
this.attachmentFiles = attachmentFiles;
315
}
316
317
/** *//**
318
* Method getAttachmentFiles.
319
*
320
* @return Map
321
*/
322
public Map getAttachmentFiles()
{
323
return attachmentFiles;
324
}
325
326
/** *//**
327
* Method setHtml.
328
*
329
* @param isHtml
330
* boolean
331
*/
332
public void setHtml(boolean isHtml)
{
333
this.isHtml = isHtml;
334
}
335
336
/** *//**
337
* Method getSenderAddress.
338
*
339
* @return String
340
*/
341
public String getSenderAddress()
{
342
return senderAddress;
343
}
344
345
/** *//**
346
* Method setSenderAddress.
347
*
348
* @param senderAddress
349
* String
350
*/
351
public void setSenderAddress(String senderAddress)
{
352
this.senderAddress = senderAddress;
353
}
354
355
public String readMailTemplate(String year, String season)
356
throws IOException
{
357
ClassLoader loder = this.getClass().getClassLoader();
358
InputStream is = loder.getResourceAsStream("t.html");
359
byte[] buf = new byte[1024 * 5];
360
is.read(buf);
361
String t = new String(buf, "utf-8");
362
t = t.replaceFirst("#year", year);
363
t = t.replaceFirst("#season", season);
364
// System.out.println(t);
365
return t;
366
}
367
368
public static void sendNoticeMail(String title, String year, String season,
369
String sender, File f)
{
370
SendMailUtil logic = new SendMailUtil();
371
try
{
372
logic.setTitle(title);
373
// logic.setMailServerAddress("10.5.1.1");
374
String temp = logic.readMailTemplate(year, season);
375
logic.setSenderAddress(sender);
376
FileReader fr = new FileReader(f);
377
378
char[] ch = new char[new Long(f.length()).intValue()];
379
fr.read(ch);
380
StringBuffer sb = new StringBuffer(new Long(f.length()).intValue());
381
for (int i = 0; i < ch.length; i++)
{
382
sb.append(ch[i]);
383
}
384
String[] all = sb.toString().split("\n");
385
386
// System.out.println(sb.toString());
387
for (int i = 0; i < all.length; i++)
{
388
if (all[i].equals(""))
{
389
continue;
390
}
391
String t = temp;
392
String[] item = all[i].split(",");
393
logic.setToAddress(item[2]);
394
// 處理內容
395
t = t.replaceFirst("#name", item[1] + "(" + item[0] + ")");
396
t = t.replaceAll("#total", item[3]);
397
t = t.replaceFirst("#tax", item[4]);
398
t = t.replaceFirst("#actualTotal", item[5]);
399
logic.setContent(t);
400
logic.sendMail();
401
}
402
} catch (Exception e)
{
403
e.printStackTrace();
404
}
405
}
406
}
4,小技巧
我
第一次發送后,發現讀取圖片的程序不對,在Outlook
2003中打開郵件,發現沒有出現圖片,搞半天也不知道是什么原因,后來我用FoxMail打開郵件,發現圖片附件上打了個叉叉,才知道是附件中的圖片讀
取不對,如果你有這樣的問題,不妨換個Mail客戶端試試。
posted on 2007-12-04 11:37
xzc 閱讀(1283)
評論(0) 編輯 收藏