1. 程式人生 > >用javaMail發送郵件

用javaMail發送郵件

tin ref exception rec 文本 test utf-8 mail urn

電子郵件協議

SMTP是推協議,負責用戶代理向郵件服務器或郵件服務器與郵件服務器間發送郵件;POP3、IMAP是拉協議,負責用戶代理從郵件服務器讀取郵件。

技術分享圖片

如何寫一封郵件

javaMail用Message對象表示一封郵件。Message類是一個抽象類,我們通常使用它的子類MimeMessage表示一封郵件。

MimeMessage構造器接受一個Session對象,Session對象表示一個會話,該對象由Session.getInstance(property)方法生成,property參數是一個Properties對象,我們借用它設置郵件傳輸的相關信息。

文本郵件

package com.weixia.SMTP;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import java.io.FileOutputStream;

public class Message_text {
    public static void main(String[] args) throws Exception {
        String from = "";   // 發件人
        String to   = "";   // 收件人
        String subject = "This ia a SMTP test mail";    // 主題
        String body = "Hello,world!";   // 郵件正文
        
        Properties property = new Properties();
        Session session = Session.getInstance(property);
        MimeMessage message = new MimeMessage(session);
        
        message.setFrom(new InternetAddress(from));
        // Message.RecipientType.TO :收件人;Message.RecipientType.CC :抄送人;Message.RecipientType.BCC :密送人
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSentDate(new Date());
        message.setSubject(subject,"UTF-8");
        message.setText(body,"UTF-8");
        message.saveChanges();
        message.writeTo(new FileOutputStream("F:\\mail.eml"));
    }
}

InternetAddress類解析郵件地址,它的構造器接受一個郵箱格式的字符串,放回一個InternetAddress對象;它的parse方法作用相同,但返回InternetAddress[],可以用來群發。

HTML格式郵件

package com.weixia.SMTP;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import java.io.FileOutputStream;

public class MailWithHtml {
    public static void main(String[] args) throws Exception {
        String from = "";
        String to   = "";
        String subject = "This ia a SMTP test mail";
        String body = "<p>Hello,world!</p>";
        
        Properties property = new Properties();
        Session session = Session.getInstance(property);
        MimeMessage message = new MimeMessage(session);
        
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSentDate(new Date());
        message.setSubject(subject,"UTF-8");
        message.setContent(body,"text/html;charset=UTF-8");
        message.saveChanges();
        message.writeTo(new FileOutputStream("F:\\mailWithHtml.eml"));
    }
}

HTML格式只需改變設置正文的方法,指明MIME類型。

含有圖片、附件或其他媒體類型的郵件

這種復雜郵件,我們把圖片、附件或其他媒體類型看作是一個BodyPart對象。因為Message對象setContent方法接受Multipart類型參數,所以必須把BodyPart封裝為Multipart對象。

封裝的方法如下圖:

技術分享圖片

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;

public class MultiMail {
    public static void main(String[] args) throws Exception {
        String from = "";
        String to   = "";
        
        Properties property = new Properties();
        Session session = Session.getInstance(property);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject("這是我用java發送的一封郵件", "UTF-8");
        message.setSentDate(new Date());
        
        // create picture node
        MimeBodyPart image = new MimeBodyPart();
        FileDataSource file = new FileDataSource("F:\\郵件.jpg");
        image.setDataHandler(new DataHandler(file));
        // 後邊引用該ID時,須使用"cid:idName"的形式,例如"<img src=‘cid:image_id‘ />"
        image.setContentID("image_id");
        
        // create text node
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("<p>This is a test picture</p><img src=‘cid:image_id‘ />","text/html;charset=UTF-8");
        
        MimeMultipart text_image = new MimeMultipart("related");
        text_image.addBodyPart(image);
        text_image.addBodyPart(text);
        // 為了添加附件,將text_image封裝為BodyPart對象
        MimeBodyPart text_image_node = new MimeBodyPart();
        text_image_node.setContent(text_image);
        
        // 創建附件
        MimeBodyPart attachment = new MimeBodyPart();
        FileDataSource attachmentFile = new FileDataSource("F:\\mail.eml");
        DataHandler handler = new DataHandler(attachmentFile);
        attachment.setDataHandler(handler);
        attachment.setFileName(attachmentFile.getName());
        
        MimeMultipart body = new MimeMultipart("mixed");
        body.addBodyPart(text_image_node);
        body.addBodyPart(attachment);
        
        message.setContent(body);
        message.saveChanges();
        
        return message;
    }
}

發送郵件

在發送郵件時,我們要設置傳輸郵件的相關信息,這裏我們使用Properties對象來設置Session會話對象。

通過Session對象獲取Transport對象,用connect方法連接郵件服務器,然後用sendMessage方法發送郵件。

SSL連接

現在郵件服務提供商通常使用SSL加密連接,設置SSL如下:

String smtpPort = "465";
Properties property = new Properties();
property.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
property.setProperty("mail.smtp.socketFactory.fallback","false");
property.setProperty("mail.smtp.socketFactory.port",smtpPort);

完整代碼如下:

package com.weixia.SMTP;

import java.util.Date;
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;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;

public class SentMultiMail {
    public static void main(String[] args) throws Exception {
        String emailAccount = "";
        String emailPassword = "";
        
        String recipient = "";
        
        String smtpHost = "smtp.sina.com";
        String smtpPort = "465";
        
        Properties property = new Properties();
        
        property.setProperty("mail.transport.protocol","smtp");
        property.setProperty("mail.smtp.host",smtpHost);
        property.setProperty("mail.smtp,port",smtpPort);
        property.setProperty("mail.smtp.auth","true");
        
        property.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        property.setProperty("mail.smtp.socketFactory.fallback","false");
        property.setProperty("mail.smtp.socketFactory.port",smtpPort);
        
        Session session = Session.getInstance(property);
        session.setDebug(true);
        MimeMessage message = createMail(session, emailAccount, recipient);
        
        Transport transport = session.getTransport();
        transport.connect(emailAccount, emailPassword);
        transport.sendMessage(message,message.getAllRecipients());
        transport.close();
    }
    
    public static MimeMessage createMail(Session session, String from, String to) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject("這是我用java發送的一封郵件", "UTF-8");
        message.setSentDate(new Date());
        
        // create picture node
        MimeBodyPart image = new MimeBodyPart();
        FileDataSource file = new FileDataSource("F:\\郵件.jpg");
        image.setDataHandler(new DataHandler(file));
        // 後邊引用該ID時,須使用"cid:idName"的形式,例如"<img src=‘cid:image_id‘ />"
        image.setContentID("image_id");
        
        // create text node
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("<p>This is a test picture</p><img src=‘cid:image_id‘ />","text/html;charset=UTF-8");
        
        MimeMultipart text_image = new MimeMultipart("related");
        text_image.addBodyPart(image);
        text_image.addBodyPart(text);
        // 為了添加附件,將text_image封裝為BodyPart對象
        MimeBodyPart text_image_node = new MimeBodyPart();
        text_image_node.setContent(text_image);
        
        // 創建附件
        MimeBodyPart attachment = new MimeBodyPart();
        FileDataSource attachmentFile = new FileDataSource("F:\\mail.eml");
        DataHandler handler = new DataHandler(attachmentFile);
        attachment.setDataHandler(handler);
        attachment.setFileName(attachmentFile.getName());
        
        MimeMultipart body = new MimeMultipart("mixed");
        body.addBodyPart(text_image_node);
        body.addBodyPart(attachment);
        
        message.setContent(body);
        message.saveChanges();
        
        return message;
    }
}

參考鏈接

JavaMail入門第二篇 創建郵件

基於JavaMail的Java郵件發送:簡單郵件發送

用javaMail發送郵件