无法使用Spring Framework发送邮件

时间:2017-03-08 11:08:21

标签: java spring email

通过发送电子邮件,我得到以下例外:

org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. b10sm22671312wmi.34 - gsmtp

以下是我用于发送电子邮件的代码:

MailRequest mailRequest = new MailRequest();
mailRequest.setSubject(messageByLocale.getMessage("mail.subject.forgetpassword"));
mailRequest.setTemplateName(messageByLocale.getMessage("mail.template.forgetpassword"));
mailRequest.setToEmail(tbNstyleloyalty.getEmail());
Map<String, Object> map = new HashMap<>();
map.put("tbNstyleloyalty", tbNstyleloyalty);
mailingConfig.sendEmail(mailRequest, map);

我的sendEmail方法是:

@Async
public void sendEmail(MailRequest mailRequest, Map<String, Object> model) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() 
    {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo(mailRequest.getToEmail());
                message.setSubject(mailRequest.getSubject());
                message.setText(VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,templatePath + mailRequest.getTemplateName() + ".vm", ApplicationConstants.CHARSET_UTF8, model),true);
         }
    };
    this.javaMailSender.send(preparator);
}

请帮助我克服这个问题。

谢谢!

4 个答案:

答案 0 :(得分:2)

可能你错过了2分中的任何一个:

  1. 在电子邮件请求中设置以下属性。
  2. props.put("mail.smtp.starttls.enable", "true");

    1. 您可能正在尝试使用端口25上的邮件服务器通过未经身份验证的连接将邮件传递给第三方。您需要让SMTP客户端连接到经过身份验证的连接。 (查看您的端口号是否用于TLS连接)

答案 1 :(得分:1)

谢谢你们的回答。你给出的所有答案都是正确的,但我无法理解我应该在哪里添加这个属性。

最后我补充说:

spring.mail.properties.mail.smtp.starttls.enable = true

到我的属性文件然后我获得了成功。

答案 2 :(得分:0)

我猜你的邮件服务器使用STARTSSL进行身份验证(如异常消息所示)。

也许这篇文章有帮助: JavaMail smtp properties (for STARTTLS)

答案 3 :(得分:0)

我认为以下代码非常简单,可用于邮寄功能

//headers
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
//code
    Session mailSession = new SmtpImpl().getSession();
    Message simpleMessage = new MimeMessage(mailSession);
    MimeMultipart multipart = new MimeMultipart("related");
    BodyPart messageBodyPart = new MimeBodyPart();
    try {
        simpleMessage.setFrom(new InternetAddress("from address")));
        simpleMessage.addRecipient(RecipientType.TO, new InternetAddress("to address"));

        String SENDCC_GET =  "person1@gmail.com,person2.gmail.com";
        String [] SENDCC = SENDCC_GET.split(",");
        InternetAddress[] addressCC = new InternetAddress[SENDCC.length];
        for (int i = 0; i < SENDCC.length; i++) {
            addressCC[i] = new InternetAddress(SENDCC[i]);
        }
        //for bcc
        simpleMessage.setRecipients(Message.RecipientType.BCC, addressCC);
        //for cc
        //simpleMessage.setRecipients(Message.RecipientType.CC, addressCC);

        String message = null;
        String subject = null;

        subject = "email subject";
        simpleMessage.setSubject(subject);
        message = "message body";
        messageBodyPart.setContent(message, "text/html; charset=utf-8");
        multipart.addBodyPart(messageBodyPart);
        simpleMessage.setContent(multipart);
        Transport.send(simpleMessage);

    } catch (AddressException e) {
        LOGGER.error("******Error while sending - Email: Address Exception::: " + e);
    } catch (MessagingException e) {
        LOGGER.error("******Error while sending - Email: Messaging Exception::: " + e);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }


    //SmtpImpl.java

    public Session getSession(){
        Properties props = new Properties();
        props.put("mail.smtp.host", EmailUtilityParam.getSmtpHostName());
        props.put("mail.smtp.port", EmailUtilityParam.getSmtpPort());
        props.put("mail.smtp.user", EmailUtilityParam.getAuthenticationId());
        props.put("mail.smtp.password", EmailUtilityParam.getAuthenticationPassword());
        props.put("mail.debug", "false");
        Session mailSession = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(EmailUtilityParam
                        .getAuthenticationId(), EmailUtilityParam
                        .getAuthenticationPassword());
            }
        });
        return mailSession;
    }

SMTP开发工具可用于开发,并将其保留为默认值,以便测试它是否有效

HOST = localhost
PORT = 25
USER(authentication id) = //empty string
PASSWORD(authentication password) = //empty string