如何使用Rest Web服务和json格式数据发送邮件

时间:2018-08-10 15:36:05

标签: json rest spring-mvc

在Spring MVC应用程序中是否可以使用REST api发送邮件,我做了很多研究,但没有找到真正说明我需要的教程。

这是我的webconfig班:

public class WebConfig {

    @Bean(name="mailSender")
    public MailSender javaMailService() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost("smtp.gmail.com");
        javaMailSender.setPort(587);
        javaMailSender.setProtocol("smtp");
        javaMailSender.setUsername("email@gmail.com");
        javaMailSender.setPassword("password");
        Properties mailProperties = new Properties();
        mailProperties.put("mail.smtp.auth", "true");
        mailProperties.put("mail.smtp.starttls.enable", "starttls");
        mailProperties.put("mail.smtp.debug", "true");
        javaMailSender.setJavaMailProperties(mailProperties);
        return javaMailSender;
    }

}  

这是我的服务类别:

@Transactional 
 @Service("mailServiceImpl")

public class MailServiceImpl implements MailService {


private JavaMailSender emailSender;

@Autowired
public void setMailSender(JavaMailSender emailSender) { 
  this.emailSender = emailSender;
}
@Override
public void sendMail(final Mail mail) {
     try {
         emailSender.send(new MimeMessagePreparator() {
             public void prepare(MimeMessage mimeMessage)
                     throws Exception {
                 MimeMessageHelper message = new 
MimeMessageHelper(mimeMessage,
                     false, "UTF-8");
             message.setFrom(mail.getFrom());
             message.addTo(mail.getTo());
             message.setSubject(mail.getSubject());
             message.setText(mail.getContent(), true);
         }
     });
 } catch (MailSendException e) {
     // your codes;
 }
 }
}

这是我的类控制器,当我尝试调用其余的api时出现错误 AVERTISSEMENT:在DispatcherServlet中,名称为“ dispatcher”的URI [/ OneToMany / Access_Denied]的HTTP请求未找到映射

    @RestController
public class SendMailController  {


 MailService mailservice ;


 private JavaMailSender mailSender;


 @RequestMapping( value="/sendMail/", method =RequestMethod.POST, produces="application/json", consumes="application/json")

 public @ResponseBody Mail add(@RequestBody Mail mail){
      mailservice.sendMail(mail);
    return mail;
 }


 }

0 个答案:

没有答案