Spring邮件服务:Maven + Spring SMTP Mail (可发送附件)

1  spring-smtp-mail.xml




    
        
        
        
        
        
        
        
        
        
        
            
                
                true
            
        
    
    







Dear %s,
Mail Content : %s
]]>


    

  2  mailConfig 类

public class mailConfig {
private MailSender mailSender;
private SimpleMailMessage simpleMailMessage;

private JavaMailSender javaMailSender;
/**
* @方法名: sendMail
* @参数名:@param subject 邮件主题
* @参数名:@param content 邮件主题内容
* @参数名:@param to 收件人Email地址
* @描述语: 发送邮件
*/
public void sendMail(String subject, String content, String to) {
simpleMailMessage.setSubject(subject); //设置邮件主题
simpleMailMessage.setTo(to); //设定收件人
simpleMailMessage.setText(content); //设置邮件主题内容

mailSender.send(simpleMailMessage); //发送邮件
}
public void sendMail_File(String subject, String mail_to,String dear, String content,String filepath){
MimeMessage mimeMessage=javaMailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage,true);
mimeMessageHelper.setFrom(simpleMailMessage.getFrom());
mimeMessageHelper.setTo(mail_to);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(String.format(
simpleMailMessage.getText(), dear, content));
FileSystemResource file = new FileSystemResource(filepath);
mimeMessageHelper.addAttachment(file.getFilename(), file);

}catch (Exception ex){
throw new MailParseException(ex);
}
javaMailSender.send(mimeMessage);
}

//Spring 依赖注入
public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
this.simpleMailMessage = simpleMailMessage;
}
//Spring 依赖注入
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
//Spring 依赖注入
public void setMailSender(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
}

  3 test 类

 @Test
    public void sendEmail(){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-smtp-mail.xml");
        mailConfig mail = (mailConfig)context.getBean("simpleMail");
        //mail.sendMail("Spring SMTP Mail Subject", "Spring SMTP Mail Text", "[email protected]");
        //mail.sendMail("标题", "内容", "收件人邮箱");
        mail.sendMail_File("test file","[email protected]","MouMou","test file","D:\\1.jpg");
    }

  

你可能感兴趣的:(Spring邮件服务:Maven + Spring SMTP Mail (可发送附件))