JavaMail發送郵件

發送郵件包含的內容有html

  1. from字段   --用於指明發件人
  2. to字段       --用於指明收件人
  3. subject字段  --用於說明郵件主題
  4. cc字段      -- 抄送,將郵件發送給收件人的同時抄送給另外一個收件人,收件人能夠看到郵件抄送給了誰
  5. bcc字段    -- 密送,將郵件發送給收件人的同時將郵件祕密發送給另外一個收件人,收件人沒法看到郵件密送給了誰

  郵件體指的就是郵件的具體內容。java

使用JavaMail建立郵件和發送郵件

JavaMail建立的郵件是基於MIME協議的。所以可使用JavaMail建立出包含圖片,包含附件的複雜郵件。spring

MIME協議簡單介紹

在咱們的實際開發當中,一封郵件既可能包含圖片,又可能包含有附件,在這樣的狀況下,RFC882文檔規定的郵件格式就沒法知足要求了。服務器

  MIME協議是對RFC822文檔的升級和補充,它描述瞭如何生產一封複雜的郵件。一般咱們把MIME協議描述的郵件稱之爲MIME郵件MIME協議描述的數據稱之爲MIME消息。
  對於一封複雜郵件,若是包含了多個不一樣的數據,MIME協議規定了要使用分隔線對多段數據進行分隔,並使用Content-Type頭字段對數據的類型、以及多個數據之間的關係進行描述。session

 

JavaMail API的簡單介紹app

  

發送一封只包含文本的簡單郵件

  package me.gacl.main;
  
  import java.util.Properties;
  import javax.mail.Message;
  import javax.mail.Session;
 import javax.mail.Transport;
  import javax.mail.internet.InternetAddress;
  import javax.mail.internet.MimeMessage;
  
 
 public class Sendmail {
 
     /**
      * @param args
      * @throws Exception 
      */
     public static void main(String[] args) throws Exception {
         
         Properties prop = new Properties();
         prop.setProperty("mail.host", "smtp.sohu.com");
         prop.setProperty("mail.transport.protocol", "smtp");
         prop.setProperty("mail.smtp.auth", "true");
         //使用JavaMail發送郵件的5個步驟
         //一、建立session
         Session session = Session.getInstance(prop);
         //開啓Session的debug模式,這樣就能夠查看到程序發送Email的運行狀態
         session.setDebug(true);
         //二、經過session獲得transport對象
         Transport ts = session.getTransport();
         //三、使用郵箱的用戶名和密碼連上郵件服務器,發送郵件時,發件人須要提交郵箱的用戶名和密碼給smtp服務器,用戶名和密碼都經過驗證以後纔可以正常發送郵件給收件人。
         ts.connect("smtp.sohu.com", "gacl", "郵箱密碼");
         //四、建立郵件
         Message message = createSimpleMail(session);
         //五、發送郵件
         ts.sendMessage(message, message.getAllRecipients());
         ts.close();
     }
     
    
     public static MimeMessage createSimpleMail(Session session)
             throws Exception {
         //建立郵件對象
         MimeMessage message = new MimeMessage(session);
         //指明郵件的發件人
         message.setFrom(new InternetAddress("gacl@sohu.com"));
         //指明郵件的收件人,如今發件人和收件人是同樣的,那就是本身給本身發
         message.setRecipient(Message.RecipientType.TO, new InternetAddress("gacl@sohu.com"));
         //郵件的標題
         message.setSubject("只包含文本的簡單郵件");
         //郵件的文本內容
         message.setContent("你好啊!", "text/html;charset=UTF-");
        //返回建立好的郵件對象
         return message;
     }
}

發送帶圖片的郵件測試

 package me.gacl.main;
  
  import java.io.FileOutputStream;
  import java.util.Properties;
  
  import javax.activation.DataHandler;
  import javax.activation.FileDataSource;
 import javax.mail.Message;
  import javax.mail.Session;
 import javax.mail.Transport;
 import javax.mail.internet.InternetAddress;
 import javax.mail.internet.MimeBodyPart;
 import javax.mail.internet.MimeMessage;
 import javax.mail.internet.MimeMultipart;
 

 public class Sendmail {
 
   
     public static void main(String[] args) throws Exception {
                 Properties prop = new Properties();
         prop.setProperty("mail.host", "smtp.sohu.com");
         prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");
         //使用JavaMail發送郵件的5個步驟
         //一、建立session
         Session session = Session.getInstance(prop);
         //開啓Session的debug模式,這樣就能夠查看到程序發送Email的運行狀態
         session.setDebug(true);
        //二、經過session獲得transport對象
         Transport ts = session.getTransport();
         //三、連上郵件服務器,須要發件人提供郵箱的用戶名和密碼進行驗證
         ts.connect("smtp.sohu.com", "gacl", "郵箱密碼");
         //四、建立郵件
         Message message = createImageMail(session);
         //五、發送郵件
         ts.sendMessage(message, message.getAllRecipients());
         ts.close();
     }
     
   
     public static MimeMessage createImageMail(Session session) throws Exception {
         //建立郵件
         MimeMessage message = new MimeMessage(session);
         // 設置郵件的基本信息
         //發件人
         message.setFrom(new InternetAddress("gacl@sohu.com"));
         //收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("xdp_gacl@sina.cn"));
         //郵件標題
         message.setSubject("帶圖片的郵件");
 
         // 準備郵件數據
         // 準備郵件正文數據
         MimeBodyPart text = new MimeBodyPart();
         text.setContent("這是一封郵件正文帶圖片<img src='cid:xxx.jpg'>的郵件", "text/html;charset=UTF-8");
         // 準備圖片數據
         MimeBodyPart image = new MimeBodyPart();
         DataHandler dh = new DataHandler(new FileDataSource("src\\1.jpg"));
         image.setDataHandler(dh);
         image.setContentID("xxx.jpg");
         // 描述數據關係
         MimeMultipart mm = new MimeMultipart();
         mm.addBodyPart(text);
        mm.addBodyPart(image);
         mm.setSubType("related");
 
         message.setContent(mm);
         message.saveChanges();
         //將建立好的郵件寫入到E盤以文件的形式進行保存
         message.writeTo(new FileOutputStream("E:\\ImageMail.eml"));
         //返回建立好的郵件
       return message;
     }
 }

發送帶附件的郵件this

 

 

 

package cn.bdqn;

import java.io.IOException;

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

import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailWithAttachment {
    private JavaMailSender mailSender; 
    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }
    
    public void send() throws MessagingException,IOException{
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom("fsb@mail.com");
        helper.setTo("wj@mail.com");
        
        helper.setSubject("haha");
        helper.setText("嘿嘿");
     
        ClassPathResource file1 = new ClassPathResource(
                                        "/cn/bdqn/attachfiles/test.doc");
        helper.addAttachment(file1.getFilename(), file1.getFile());
        
        ClassPathResource file2 = new ClassPathResource(
                                        "/cn/bdqn/attachfiles/test.doc");
        helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()),file2.getFile());
        mailSender.send(mimeMessage);
    }
}

 大配置:編碼

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="192.168.8.71"></property><!-- 服務器 -->
        <property name="port" value="25"></property><!-- 端口 -->
        <property name="username" value="fsb@mail.com"></property><!-- 用戶名 -->
        <property name="password" value="fsb"></property><!-- 密碼 -->
        <property name="protocol" value="smtp" ></property><!-- 協議 -->
        <property name="defaultEncoding" value="utf-8"></property><!-- 默認編碼 -->
        <property name="javaMailProperties">
            <props>
                <!-- 設置SMTP服務器須要用戶驗證  -->
                <prop key="mail.smtp.auth">true</prop>
            </props>
        </property>
    </bean>
    
    <bean id="mailWithAttachment" class="cn.bdqn.MailWithAttachment">
        <property name="mailSender" ref="mailSender"></property>
    </bean>

</beans>

測試:spa

package cn.bdqn;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MailTest {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        
        try{
            MailWithAttachment mailWithAttach = (MailWithAttachment)context.getBean("mailWithAttachment");
            mailWithAttach.send();
            System.out.println(0);
        }catch(Exception e){
            System.out.print(e.toString());
        }
    }
}    
相關文章
相關標籤/搜索