首页 > 代码库 > spring 发送邮件代码示例(带附件和不带附件的)
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("xxxxy@xxxxy.com"); simpleMailMessage.setTo("xxxxy@xxxxy.com"); mailSender.send(simpleMailMessage); return "Mail Sent"; } @RequestMapping(value = "/sendMessageWithAttachment", method = RequestMethod.GET) @ResponseBody public String sendMessageWithAttachment(){ simpleMailMessage=new SimpleMailMessage(); simpleMailMessage.setFrom("xxxxy@xxxxy.com"); simpleMailMessage.setTo("xxxxy@xxxxy.com"); 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 发送邮件代码示例(带附件和不带附件的)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。