zhang964761032 发表于 2013-2-7 18:12:54

javaMail,

Java发送邮件(三)
随着学习的进一步深入,我们这次来探讨带有图片和附件的邮件的生成及发送。
邮件发送的原理如图:


代码大致如下:
Code:
1.public static void main(String[] args) throws Exception{   
2.      // 创建属性   
3.      Properties props = new Properties();   
4.      props.put("mail.smtp.host", "smtp.sohu.com");// 设置smtp主机   
5.      props.put("mail.smtp.auth", "true");// 使用smtp身份验证   
6.      // Session session = Session.getInstance(props);   
7.      Session session = Session.getInstance(props, new Authenticator() {   
8.            public PasswordAuthentication getPasswordAuthentication() {   
9.                return new PasswordAuthentication("xxxxzfdw123@sohu.com",   
10.                        "*****");//发件箱的账号和密码   
11.            }   
12.      });   
13.      MimeMessage mime = new MimeMessage(session);   
14.      //设置发件箱地址   
15.      mime.setFrom(new InternetAddress("xxxxzfdw123@sohu.com"));   
16.      //设置收件箱地址   
17.      mime.setRecipient(Message.RecipientType.TO, new InternetAddress("112345323@qq.com"));   
18.      //设置主题   
19.      mime.setSubject("欢迎,Jhon","UTF-8");   
20.      //设置正文   
21.      MimeBodyPart part = new MimeBodyPart();   
22.      part.setContent("欢迎归来!<br><img src='cid:xxx.jpg'>","text/html;charset=UTF-8");//引用的图片id   
23.      //设置附件   
24.      MimeBodyPart attch= new MimeBodyPart();   
25.      DataHandler dh = new DataHandler(new FileDataSource("other\\我们说好的.mp3"));   //引用项目中other文件夹中的歌曲   
26.      attch.setDataHandler(dh);   
27.      String name = dh.getName();   
28.      //设置附件的名称   
29.      attch.setFileName(MimeUtility.encodeText(name));   
30.      //设置图片   
31.      MimeBodyPart image = new MimeBodyPart();   
32.      image.setDataHandler(new DataHandler(new FileDataSource("images\\589.jpg")));//项目中images文件夹中的图片589.jpg   
33.      image.setContentID("xxx.jpg");   
34.      //描述关系   
35.      MimeMultipart mm = new MimeMultipart();   
36.      mm.addBodyPart(part);   
37.      mm.addBodyPart(image);   
38.      mm.addBodyPart(attch);   
39.      mm.setSubType("mixed");   
40.            
41.      mime.setContent(mm);   
42.      mime.saveChanges();   
43.            
44.      Transport.send(mime);//发送邮件   
45.            
46.    }   
如有不知道或不清楚的类和方法可参考官方API。
以上就是今天的收获,希望对大家有用!
如有问题请发邮件至964761032@qq.com。欢迎交流探讨。
页: [1]
查看完整版本: javaMail,