Spring3.2下使用JavaMailSenderImpl類發送郵件


1、JavaMailSenderImpl類

  Spring的郵件發送的核心是MailSender接口,在Spring3.0中提供了一個實現類JavaMailSenderImpl,這個類是發送郵件的核心類。

可以通過在配置文件中配置使用,當然也可以自己硬編碼到代碼中。

2、准備工作

  搭建spring環境,此處默認學習者已搭建成功。

  下載JavaMail jar包,導入工程。

  http://www.oracle.com/technetwork/java/javamail/index-138643.html

3、案例代碼

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class SpringMailSender {
    // Spring的郵件工具類,實現了MailSender和JavaMailSender接口
    private JavaMailSenderImpl mailSender;

    //使用Velocity模板,需要Velocity的jar包,然后需要聲明一個VelocityEngine對象
    private VelocityEngine velocityEngine;
    
    /**
     * 創建郵件發送器
     */
    public SpringMailSender() {
        // 初始化JavaMailSenderImpl,當然推薦在spring配置文件中配置,這里是為了簡單
        mailSender = new JavaMailSenderImpl();
        // 設置參數
        mailSender.setHost("smtp.qq.com");
        mailSender.setUsername("123456789@qq.com");
        mailSender.setPassword("555555");
        
        //聲明一個VelocityEngine對象后,需要在構造函數中初始化(IoC is optional)
        // Velocity的參數,通過VelocityEngineFactoryBean創建VelocityEngine,也是推薦在配置文件中配置的
        Properties props = System.getProperties();
        props.put("resource.loader", "class");
        props.put("class.resource.loader.class",
                        "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        VelocityEngineFactoryBean v = new VelocityEngineFactoryBean();
        v.setVelocityProperties(props);
        try {
            velocityEngine = v.createVelocityEngine();
        } catch (VelocityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 
    * 方法名: simpleSend
    * 方法作用: TODO 簡單郵件發送
    * 創建人:Jxufe HeHaiYang
    * 創建時間:2015-2-7 下午06:47:30   
    * @param @throws Exception    
    * 返回值類型: void    
    * @throws
     */
    public void simpleSend() throws Exception {
        // 構建簡單郵件對象
        //SimpleMailMessages實現了MimeMessageHelper,為普通郵件模板,支持文本。
        SimpleMailMessage smm = new SimpleMailMessage();
        // 設定郵件參數
        smm.setFrom(mailSender.getUsername());
        smm.setTo("234567890@qq.com");
        smm.setSubject("Hello world");
        smm.setText("nice !");
        // 發送郵件
        mailSender.send(smm);
    }
    
    
    /**
     * 
    * 方法名: attachedSend
    * 方法作用: TODO 帶附件的郵件發送
    * 創建人:Jxufe HeHaiYang
    * 創建時間:2015-2-7 下午06:47:22   
    * @param @throws MessagingException    
    * 返回值類型: void    
    * @throws
     */
    public void attachedSend() throws MessagingException {
        //使用JavaMail的MimeMessage,支付更加復雜的郵件格式和內容
        //MimeMessages為復雜郵件模板,支持文本、附件、html、圖片等。
        MimeMessage msg = mailSender.createMimeMessage();
        //創建MimeMessageHelper對象,處理MimeMessage的輔助類
        MimeMessageHelper helper = new MimeMessageHelper(msg, true);
        //使用輔助類MimeMessage設定參數
        helper.setFrom(mailSender.getUsername());
        helper.setTo("234567890@qq.com");
        helper.setSubject("Hello Attachment");
        helper.setText("This is a mail with attachment");
        //加載文件資源,作為附件
        //文件地址相對應src目錄
        ClassPathResource file = new ClassPathResource("ehcache.xsd");
        //加入附件
        helper.addAttachment("ehcache.xsd", file);
        
        //發送郵件
        mailSender.send(msg);
    }
    
    /**
     * 
    * 方法名: richContentSend
    * 方法作用: TODO 發送富文本郵件
    * 創建人:Jxufe HeHaiYang
    * 創建時間:2015-2-7 下午06:47:14   
    * @param @throws MessagingException    
    * 返回值類型: void    
    * @throws
     */
    public void richContentSend() throws MessagingException {
        MimeMessage msg = mailSender.createMimeMessage();
     
        MimeMessageHelper helper = new MimeMessageHelper(msg, true);
     
        helper.setFrom(mailSender.getUsername());
        helper.setTo("234567890@qq.com");
        helper.setSubject("郵件標題");
        //第二個參數true,表示text的內容為html,然后注意<img/>標簽,src='cid:file','cid'是contentId的縮寫,'file'是一個標記,
需要在后面的代碼中調用MimeMessageHelper的addInline方法替代成文件
helper.setText( "<body><p style='color:red;'>Hello Html Email</p><img src='cid:file'/></body>", true); //文件地址相對應src目錄 ClassPathResource file = new ClassPathResource("logo.png"); //文件地址對應系統目錄 // FileSystemResource file = new FileSystemResource("C:\\Users\\HIYOUNG\\Desktop\\logo.png"); helper.addInline("file", file); mailSender.send(msg); } /** * * 方法名: templateSend * 方法作用: TODO 使用Velocity模板發送郵件 * 創建人:Jxufe HeHaiYang * 創建時間:2015-2-7 下午06:47:05 * @param @throws MessagingException * 返回值類型: void * @throws */ public void templateSend() throws MessagingException { // 聲明Map對象,並填入用來填充模板文件的鍵值對 Map<String, Object> model = new HashMap<String, Object>(); model.put("user", "hehaiyang"); model.put("content", "good evening !"); //Spring提供的VelocityEngineUtils將模板進行數據填充,並轉換成普通的String對象 //文件地址相對應src目錄 String emailText = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, "/velocity/mail.vm", model); // 和上面一樣的發送郵件的工作 MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, true); helper.setFrom(mailSender.getUsername()); helper.setTo("234567890@qq.com"); helper.setSubject("Rich content mail"); helper.setText(emailText, true); mailSender.send(msg); } }

Velocity模板mail.vm

<html>
<head>
<style type="text/css">
h4{
    color:red;
    background:#efefef;
}
</style>
</head>
<body>
  <h4>${user} </h4>
  <p><p>
  <i>${content}</i>
</body>
</html>

4、可能遇到的問題

異常1:

spring 發送郵件時遇到異常org.springframework.mail.MailAuthenticationException
org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException 

解決方法:

  如果遇到所示異常,請檢查你所配置的發送郵箱,有沒有對外開放POP3/SMTP服務。

異常2:

    Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream  
        at javax.mail.Session.loadProvidersFromStream(Session.java:928)  
        at javax.mail.Session.access$000(Session.java:174)  
        at javax.mail.Session$1.load(Session.java:870)  
        at javax.mail.Session.loadResource(Session.java:1084)  
        at javax.mail.Session.loadProviders(Session.java:889)  
        at javax.mail.Session.<init>(Session.java:210)  
        at javax.mail.Session.getInstance(Session.java:249)  
   

解決方法:

  如果你使用的是JDK1.5以上環境,那么你應該會遇到所示異常,因為環境下javaee.jar包與java mail 包有沖突。

  找到javaee.jar包刪除里面的mail 包以及mail下屬的包,去除沖突。

5、測試

  更改SpringMailSender調用的方法,逐個測試發送郵件。

public class SenderTest {

     public static void main(String[] args){
        try {
            SpringMailSender m=new SpringMailSender();
            m.richContentSend();
            System.out.println("發送成功!");
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        
     }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM