将Spring Boot配置为使用我的Gmail smtp

时间:2018-11-16 18:09:03

标签: java spring-boot smtp gmail

是否可以通过application.properties文件中的条目替换以下代码:

属性props = this.mailSender.getJavaMailProperties(); props.put(“ mail.smtp.starttls.enable”,“ true”);

致谢

1 个答案:

答案 0 :(得分:0)

只需将它们放在application.properties上。就是其他东西。

#SMTP configuration
    spring.mail.host=smtp.gmail.com
    spring.mail.port=587
    spring.mail.username=klklk@gmail.com
    spring.mail.password=lkkl
    spring.mail.properties.mail.smtp.starttls.enable=true
    spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com
    spring.mail.properties.mail.smtp.starttls.required=true
    spring.mail.properties.mail.smtp.auth=true
    spring.mail.properties.mail.smtp.connectiontimeout=5000
    spring.mail.properties.mail.smtp.timeout=5000
    spring.mail.properties.mail.smtp.writetimeout=5000

写这样的邮件发件人类

@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    public JavaMailSender emailSender;
    private final String imageLink = "images/teddy.jpeg";
    private final String imageNameToSend = "teddy.jpeg";

    @Override
    public void sendSimpleMessage(String to, String subject, String text) throws IOException, MessagingException {
        MimeMessage message = emailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);


            helper.setTo(to);
            helper.setSubject(subject);

            FileSystemResource file
                    = new FileSystemResource(new ClassPathResource(imageLink).getFile());
            helper.addAttachment(imageNameToSend, file);

            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(text, "text/html");


            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart);
            emailSender.send(message);
        } catch (MessagingException | IOException e ) {
            log.info("Exception catched {}",e);
            throw e;
        }
    }
}

电子邮件服务将是这样

public interface EmailService {
    void sendSimpleMessage(
            String to, String subject, String text) throws IOException, MessagingException;
}

将以下库添加到build.gradle文件中,或者如果您正在使用其他构建工具,请将此库添加到相应文件中

compile('org.springframework.boot:spring-boot-starter-mail:1.5.9.RELEASE')