通过Spring mvc Application发送电子邮件

时间:2018-04-06 04:24:13

标签: spring email spring-mvc frameworks sendmail

有人可以帮我发送 spring framework 的电子邮件吗?最近我用谷歌搜索,但没有得到完美的解决方案。我想要完美的解决方案我在跟踪一些例子时遇到错误。我正在使用 spring framework version 4.3.6.RELEASE

1 个答案:

答案 0 :(得分:0)

  

添加以下Maven依赖

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4</version>
    </dependency> 
  

以下是发送电子邮件的示例代码

import java.util.Properties;

import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

public class TestClass {


    public String sendEmail() throws Exception {

        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();

        mailSender.setHost("your host");
        mailSender.setPort(587);
        mailSender.setUsername("Your email");
        mailSender.setPassword("password");

        Properties javaMailProperties = new Properties();
        javaMailProperties.put("mail.smtp.starttls.enable", "false");
        javaMailProperties.put("mail.smtp.auth", "true");
        javaMailProperties.put("mail.transport.protocol", "smtp");
        javaMailProperties.put("mail.debug", "true");

        mailSender.setJavaMailProperties(javaMailProperties);
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                message.setTo("To");
                message.setFrom(mailSender.getUsername());
                message.setSubject("Subject");
                message.setBcc(mailSender.getUsername());
                message.setText("Body", true);
            }
        };
        mailSender.send(preparator);

        return "Mail Sent Successfully.";
    }

}

你需要设置一些下面的参数

  • 主机名
  • 端口号
  • 电子邮件地址
  • 密码
  • 主题

它可以帮助您通过Spring应用程序发送电子邮件