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 // ---------图片处理开始!!!!!!!!!!!!!!!!
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 // ---------图片处理结束!!!!!!!!!!!!!!!!
30
31 // 把mm作为消息对象的内容
32 msg.setContent(mm); 仔细看代码中的注释吧,相信大有帮助。
3,一个实际应用的完整代码
要求根据一个格式文件和模版,发一封漂亮的邮件,所以需要用到HTML格式来发送邮件。不多说了,看代码吧!
1import java.io.ByteArrayOutputStream;
2import java.io.File;
3import java.io.FileReader;
4import java.io.IOException;
5import java.io.InputStream;
6import java.util.Date;
7import java.util.HashMap;
8import java.util.Map;
9import java.util.Properties;
10
11import javax.activation.DataHandler;
12import javax.mail.Address;
13import javax.mail.BodyPart;
14import javax.mail.internet.InternetAddress;
15import javax.mail.internet.MimeBodyPart;
16import javax.mail.internet.MimeMessage;
17import javax.mail.internet.MimeMultipart;
18import javax.mail.util.ByteArrayDataSource;
19
20/** *//**
21 *
22 * @author robin
23 * @version $Revision: 1.4 $
24 */
25public 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-03 16:42
Robin's Programming World 阅读(1475)
评论(4) 编辑 收藏