首页 > 代码库 > 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 发送邮件代码示例(带附件和不带附件的)