Spring中使用JavaMailSenderImpl发送邮件_学习记录

Spring中使用JavaMailSenderImpl发送邮件

原文链接:https://baike.xsoftlab.net/view/648.html

ApplicationContext.xml:








  
   
       true
       [email protected]
       true
   


使用注解从Spring容器中注入mailSender对象:

@Autowired
private JavaMailSenderImpl sender;

准备一封简单的邮件:

// 构建简单邮件对象,见名知意
SimpleMailMessage smm = new SimpleMailMessage();
// 设定邮件参数
smm.setFrom(sender.getUsername());
smm.setTo("[email protected]");
smm.setSubject("Hello world");
smm.setText("Hello world via spring mail sender");

发送邮件:

sender.send(smm);

如果你想发送带有附件的邮件:

 
/**
 * 发送带附件的邮件,可指定附件名
 * @param to
 * @param subject
 * @param text
 * @param file
 * @throws MessagingException
 */
public static void send(String to,String subject,String text,
     String fileName,File file) throws MessagigException{
    //使用JavaMail的MimeMessage,支付更加复杂的邮件格式和内容
    MimeMessage msg = sender.createMimeMessage();
 
    //创建MimeMessageHelper对象,处理MimeMessage的辅助类
    MimeMessageHelper helper = new MimeMessageHelper(msg, true);
 
    //使用辅助类MimeMessage设定参数
    helper.setFrom(sender.getUsername());
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(text,true);
         
    //加入附件
    if(file!=null)helper.addAttachment(fileName, file);
 
    //发送邮件
    sender.send(msg);
}

 

 

更多参考链接:

https://blog.csdn.net/csdn_xuexiaoqiang/article/details/73730649

https://blog.csdn.net/smcwwh/article/details/7095027

 

你可能感兴趣的:(java)