Spring发送邮件
1 public class SpringMailSender { 2 private Log log = LogFactory.getLog(this.getClass()); 3 private JavaMailSenderImpl sender; 4 5 /** 6 * 在构造器中初始化JavaMailSenderImpl 7 */ 8 public SpringMailSender(){ 9 sender = new JavaMailSenderImpl();
/*以下参数为从配置文件中读取,也可直接指定*/ 10 sender.setHost(CacheMapUtil.getConfigPropMap().get("mailhost").toString()); 11 sender.setUsername(CacheMapUtil.getConfigPropMap().get("mailusername").toString()); 12 sender.setPassword(CacheMapUtil.getConfigPropMap().get("mailpassword").toString()); 13 } 14 15 /** 16 * 发送简单邮件 17 */ 18 public void sendSimpleEmail(String toUserAddress,String url){ 19 SimpleMailMessage message = new SimpleMailMessage(); 20 21 message.setFrom(sender.getUsername()); 22 message.setTo(toUserAddress); 23 message.setSubject("密码找回链接"); 24 message.setText("点击下面链接找回密码:"+url); 25 26 sender.send(message); 27 } 28 29 /** 30 * 发送富文本邮件 31 */ 32 public void sendRichEmail(String toUserAddress,String url){ 33 MimeMessage message = sender.createMimeMessage(); 34 try { 35 MimeMessageHelper helper = new MimeMessageHelper(message,true,"utf-8"); 36 helper.setFrom(sender.getUsername()); 37 helper.setTo(toUserAddress); 38 helper.setSubject("密码找回链接"); 39 helper.setText("<html><body>点击或复制 以下链接进行密码修改:</br>"+url+"<br/></body></html>",true); 40 FileSystemResource res = new FileSystemResource(new File("C:\\a.jpg")); 41 helper.addInline("identifier1234", res); 42 43 sender.send(message); 44 } catch (MessagingException e) { 45 log.error("邮件发送失败,错误信息为:"+e); 46 } 47 48 }55 }