`
zl198751
  • 浏览: 273648 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring 发送 Email

阅读更多

首先介绍下Email的发送流程:

需要选中smtp邮件服务器,Yahoo不提供免费的smtp服务器,Gmail的可以;需要接送邮件就需要配置pop服务器,Yahoo支持免费 的pop服务器,Gmail一样支持。  介绍下在OutLook中配置Gmail的邮件服务,gmail的smtp端口是465,需要ssl连接,pop是995也是ssl连接,并且需要服务器 身份验证(这个需要在outlook中勾选)。配置好后可以发送和接收和邮件了。

下面说下如何用java发送邮件:

Spring的配置文件中初始化 JavaMailSenderImpl或者直接在类中new都可以

 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"></bean>

下面是利用freemarkder发送email的简单示例。

@Service
public class EmailTestSender {
   
    @Autowired
    @Qualifier("mailSender")
    private JavaMailSenderImpl sender;
   
    public void test() throws MessagingException, TemplateException, IOException {
        sender.setHost("smtp.gmail.com");
        sender.setUsername("******");
        sender.setPassword("******");
        sender.setPort(465);
       
        Properties config = new Properties();
        config.put("mail.smtp.auth", "true");
        config.put("mail.smtp.timeout", 1000 * 60);
        config.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        config.put("mail.smtp.socketFactory.fallback", "false");
        config.put("mail.smtp.socketFactory.port", new Integer(465));
       
        sender.setJavaMailProperties(config);
       
        MimeMessage message = sender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
       
        helper.setFrom("******");
        helper.setTo("******");
        helper.setSubject("Test By Java");
        helper.setText(getContent(), true);
        sender.send(message);
    }
   
    public String getContent() throws TemplateException, IOException {
        Configuration g = new Configuration();
        g.setEncoding(Locale.getDefault(), "UTF-8");
        g.setDirectoryForTemplateLoading(new File("./"));
       
        Template template = g.getTemplate("content.ftl");
       
        StringWriter out = new StringWriter();
        Map<String, String> data = new HashMap<String, String>();
        data.put("test", "I am in freemarker.");
        template.process(data, out);
        return out.toString();
    }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics