java发送邮件的方法
转载自:http://haiyang08101.iteye.com/blog/1775552
代码1:使用spring的邮件服务
1 /** 2 *用spring mail 发送邮件,依赖jar:spring.jar,activation.jar,mail.jar 3 */ 4 public static void sendFileMail() throws MessagingException { 5 JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); 6 7 // 设定mail server 8 senderImpl.setHost("smtp.126.com"); 9 senderImpl.setUsername("yuhan0"); 10 senderImpl.setPassword("******"); 11 // 建立HTML邮件消息 12 MimeMessage mailMessage = senderImpl.createMimeMessage(); 13 // true表示开始附件模式 14 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8"); 15 16 // 设置收件人,寄件人 17 messageHelper.setTo("slimes@126.com"); 18 messageHelper.setFrom("yuhan0@126.com"); 19 messageHelper.setSubject("测试邮件!"); 20 // true 表示启动HTML格式的邮件 21 messageHelper.setText("<html><head></head><body><h1>你好:附件!!</h1></body></html>", true); 22 23 FileSystemResource file1 = new FileSystemResource(new File("d:/logo.jpg")); 24 FileSystemResource file2 = new FileSystemResource(new File("d:/读书.txt")); 25 // 添加2个附件 26 messageHelper.addAttachment("logo.jpg", file1); 27 28 try { 29 //附件名有中文可能出现乱码 30 messageHelper.addAttachment(MimeUtility.encodeWord("读书.txt"), file2); 31 } catch (UnsupportedEncodingException e) { 32 e.printStackTrace(); 33 throw new MessagingException(); 34 } 35 // 发送邮件 36 senderImpl.send(mailMessage); 37 System.out.println("邮件发送成功....."); 38 39 }
代码2:使用apache commons-email 发送邮件
1 /** 2 *用apache commons-email 发送邮件 3 *依赖jar:commons-email.jar,activation.jar,mail.jar 4 */ 5 public static void sendMutiMessage() { 6 7 MultiPartEmail email = new MultiPartEmail(); 8 String[] multiPaths = new String[] { "D:/1.jpg", "D:/2.txt" }; 9 10 List<EmailAttachment> list = new ArrayList<EmailAttachment>(); 11 for (int j = 0; j < multiPaths.length; j++) { 12 EmailAttachment attachment = new EmailAttachment(); 13 //判断当前这个文件路径是否在本地 如果是:setPath 否则 setURL; 14 if (multiPaths[j].indexOf("http") == -1) { 15 attachment.setPath(multiPaths[j]); 16 } else { 17 try { 18 attachment.setURL(new URL(multiPaths[j])); 19 } catch (MalformedURLException e) { 20 e.printStackTrace(); 21 } 22 } 23 attachment.setDisposition(EmailAttachment.ATTACHMENT); 24 attachment.setDescription("Picture of John"); 25 list.add(attachment); 26 } 27 28 try { 29 // 这里是发送服务器的名字: 30 email.setHostName("smtp.126.com"); 31 // 编码集的设置 32 email.setCharset("utf-8"); 33 // 收件人的邮箱 34 email.addTo("slimes@126.com"); 35 // 发送人的邮箱 36 email.setFrom("yuhan0@126.com"); 37 // 如果需要认证信息的话,设置认证:用户名-密码。分别为发件人在邮件服务器上的注册名称和密码 38 email.setAuthentication("yuhan0", "******"); 39 email.setSubject("这是一封测试邮件"); 40 // 要发送的信息 41 email.setMsg("<b><a href=\"http://www.baidu.com\">邮件测试内容</a></b>"); 42 43 for (int a = 0; a < list.size(); a++) //添加多个附件 44 { 45 email.attach(list.get(a)); 46 } 47 // 发送 48 email.send(); 49 } catch (EmailException e) { 50 e.printStackTrace(); 51 } 52 }