1. 程式人生 > >使用JavaMail傳送簡單郵件

使用JavaMail傳送簡單郵件

使用Spring+JavaMail,把傳送郵件做成了一個http服務

@RequestMapping(value = "/mail", method = RequestMethod.POST, produces={"application/json;charset=UTF-8"})
public String send(HttpServletRequest request) {
    try {
        //valid mail body
        MailBody mailBody = new MailBody(request);
        mailBody.valid();
        //load configuration
        Properties mailProperties = new Properties();
        mailProperties.put("mail.smtp.host", channelConfig.getHost());
        mailProperties.put("mail.smtp.port", channelConfig.getPort());
        mailProperties.put("mail.smtp.auth", "true");
        mailProperties.put("mail.transport.protocol", "smtp");
        mailProperties.put("mail.smtp.starttls.enable", "true");
        mailProperties.put("mail.smtp.ssl.checkserveridentity", "false");
        mailProperties.put("mail.smtp.ssl.trust", channelConfig.getHost());
        Session session = Session.getInstance(mailProperties, 
                new Authenticator(channelConfig.getUsername(), channelConfig.getPassword()));
        //郵件資訊
        MimeMessage message = new MimeMessage(session);
        //發件人
        message.setFrom(new InternetAddress(channelConfig.getSendForm()));
        //收件人
        List<String> sendToStrList = mailBody.getSendTo();
        InternetAddress[] sendToList = new InternetAddress[sendToStrList.size()];
        for (int index = 0; index < sendToStrList.size(); index++) {
            sendToList[index] = new InternetAddress(sendToStrList.get(index));
        }
        //InternetAddress[] sendToList = {new InternetAddress("
[email protected]
")}; message.setRecipients(MimeMessage.RecipientType.TO, sendToList); //標題 message.setSubject(mailBody.getSubject()); //正文 message.setText(mailBody.getText()); message.saveChanges(); Transport.send(message); return (new ResponseJson<String>(200, "success.", null)).toString(); } catch (Exception ex) { logger.error(ex.getMessage()); return (new ResponseJson<String>(500, ex.getMessage(), null)).toString(); } }

JavaMail文件地址:

https://javaee.github.io/javamail/

可以看我的github專案:

https://github.com/lizhibin205/spring_mail_service