spring 发送邮件代码示例(带附件和不带附件的)
Posted 一天不进步,就是退步!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring 发送邮件代码示例(带附件和不带附件的)相关的知识,希望对你有一定的参考价值。
import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.MailParseException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/api") public class SendMailController { @Autowired private JavaMailSender mailSender; private SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); @RequestMapping(value = "/sendmsg", method = RequestMethod.GET) @ResponseBody public String sendMessage(){ simpleMailMessage.setSubject("~-Test-~"); simpleMailMessage.setText("test"); simpleMailMessage.setFrom("[email protected]"); simpleMailMessage.setTo("[email protected]"); mailSender.send(simpleMailMessage); return "Mail Sent"; } @RequestMapping(value = "/sendMessageWithAttachment", method = RequestMethod.GET) @ResponseBody public String sendMessageWithAttachment(){ simpleMailMessage=new SimpleMailMessage(); simpleMailMessage.setFrom("[email protected]"); simpleMailMessage.setTo("[email protected]"); simpleMailMessage.setSubject("xxxxy" ); simpleMailMessage.setText("dear davidwangwei456"+"\r\n xxxxy" +",见附件所示"); sendMailWithAttachment("xxxxy.xls",simpleMailMessage); return "Mail Sent"; } private void sendMailWithAttachment(String fileName,SimpleMailMessage simpleMailMessage) { // 发送邮件 MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message , true, "UTF-8"); helper.setFrom(simpleMailMessage.getFrom()); helper.setTo(simpleMailMessage.getTo()); helper.setSubject(simpleMailMessage.getSubject()); helper.setText(simpleMailMessage.getText()); FileSystemResource file = new FileSystemResource(fileName); helper.addAttachment(file.getFilename(), file); } catch (MessagingException e) { throw new MailParseException(e); } mailSender.send(message); } @RequestMapping(value = "/hello" , method = RequestMethod.GET) @ResponseBody public String getHello(){ return "Hello"; }
以上是关于spring 发送邮件代码示例(带附件和不带附件的)的主要内容,如果未能解决你的问题,请参考以下文章