Spring 发送 Email

本文转自:http://zl198751.iteye.com/blog/757617

看到了本文,收获颇丰,感谢之至!

首先介绍下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();
    }

}

 
上一篇:Openstack_后端存储平台Ceph


下一篇:HDU1166 敌兵布阵_线段树