1. 程式人生 > >JAVA傳送郵件最全示例

JAVA傳送郵件最全示例

傳送郵件是我們在程式開發中很常見的功能,比如註冊通知、找回密碼等,在網上也有很多關於JAVA傳送郵件的示例,但多數都是隻介紹了其中的一部分,今天為大家提供一些JAVA傳送各種形式郵件的示例,供大家學習參考。

JAVA Mail

JAVA Mail是很常用的用於傳送郵件的包,我們可以從這裡獲取,或者在maven中新增如下配置:

<dependency>
   <groupId>com.sun.mail</groupId>
   <artifactId>javax.mail</artifactId>
   <version
>
1.5.5</version> </dependency>

如果使用junit測試還需要新增:

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.8.2</version>
</dependency>

示例程式碼如下:

package com.gujin.mail;

import java.io.File;
import java.util.Date;
import
java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; 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; import javax.mail.internet.MimeUtility; public class MailSenderTest { private String host = "smtp.126.com"; private String port = "25"; private String userName = ""; private String password = ""; private String to = ""; /** * 傳送文字郵件 * * @throws Exception */ public void sendTextMail() throws Exception { Properties pro = System.getProperties(); pro.put("mail.smtp.host", host); pro.put("mail.smtp.port", port); pro.put("mail.smtp.auth", "true"); // 根據郵件會話屬性和密碼驗證器構造一個傳送郵件的session Session sendMailSession = Session.getDefaultInstance(pro, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); // 根據session建立一個郵件訊息 Message mailMessage = new MimeMessage(sendMailSession); // 設定郵件訊息的傳送者 mailMessage.setFrom(new InternetAddress(userName)); // 建立郵件的接收者地址,並設定到郵件訊息中 mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 設定郵件訊息的主題 mailMessage.setSubject("Test Email"); // 設定郵件訊息傳送的時間 mailMessage.setSentDate(new Date()); // 設定郵件訊息的主要內容 mailMessage.setText("this is a test Text mail"); // 傳送郵件 Transport.send(mailMessage); } /** * 傳送Html郵件 * * @throws Exception */ public void sendHtmlMail() throws Exception { Properties pro = System.getProperties(); pro.put("mail.smtp.host", host); pro.put("mail.smtp.port", port); pro.put("mail.smtp.auth", "true"); // 根據郵件會話屬性和密碼驗證器構造一個傳送郵件的session Session sendMailSession = Session.getDefaultInstance(pro, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); // 根據session建立一個郵件訊息 Message mailMessage = new MimeMessage(sendMailSession); // 設定郵件訊息的傳送者 mailMessage.setFrom(new InternetAddress(userName)); // 建立郵件的接收者地址,並設定到郵件訊息中 mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 設定郵件訊息的主題 mailMessage.setSubject("Test Email"); // 設定郵件訊息傳送的時間 mailMessage.setSentDate(new Date()); // MiniMultipart類是一個容器類,包含MimeBodyPart型別的物件 Multipart mainPart = new MimeMultipart(); // 建立一個包含HTML內容的MimeBodyPart BodyPart html = new MimeBodyPart(); // 設定HTML內容 html.setContent( "<html><body><img src='http://avatar.csdn.net/A/C/A/1_jianggujin.jpg'/><div>this is a HTML email.</div></body></html>", "text/html; charset=utf-8"); mainPart.addBodyPart(html); // 將MiniMultipart物件設定為郵件內容 mailMessage.setContent(mainPart); // 傳送郵件 Transport.send(mailMessage); } /** * 傳送內嵌圖片郵件 * * @throws Exception */ public void sendImageMail() throws Exception { Properties pro = System.getProperties(); pro.put("mail.smtp.host", host); pro.put("mail.smtp.port", port); pro.put("mail.smtp.auth", "true"); // 根據郵件會話屬性和密碼驗證器構造一個傳送郵件的session Session sendMailSession = Session.getDefaultInstance(pro, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); // 根據session建立一個郵件訊息 Message mailMessage = new MimeMessage(sendMailSession); // 設定郵件訊息的傳送者 mailMessage.setFrom(new InternetAddress(userName)); // 建立郵件的接收者地址,並設定到郵件訊息中 mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 設定郵件訊息的主題 mailMessage.setSubject("Test Email"); // 設定郵件訊息傳送的時間 mailMessage.setSentDate(new Date()); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<html><body><img src='cid:image'/><div>this is a HTML email.</div></body></html>"; messageBodyPart.setContent(htmlText, "text/html; charset=utf-8"); multipart.addBodyPart(messageBodyPart); MimeBodyPart imageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource("1_jianggujin.jpg"); imageBodyPart.setDataHandler(new DataHandler(fds)); imageBodyPart.setContentID("image"); multipart.addBodyPart(imageBodyPart); mailMessage.setContent(multipart); // 傳送郵件 Transport.send(mailMessage); } /** * 傳送附件郵件 * * @throws Exception */ public void sendAttachmentMail() throws Exception { Properties pro = System.getProperties(); pro.put("mail.smtp.host", host); pro.put("mail.smtp.port", port); pro.put("mail.smtp.auth", "true"); // 根據郵件會話屬性和密碼驗證器構造一個傳送郵件的session Session sendMailSession = Session.getDefaultInstance(pro, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); // 根據session建立一個郵件訊息 Message mailMessage = new MimeMessage(sendMailSession); // 設定郵件訊息的傳送者 mailMessage.setFrom(new InternetAddress(userName)); // 建立郵件的接收者地址,並設定到郵件訊息中 mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 設定郵件訊息的主題 mailMessage.setSubject("Test Email"); // 設定郵件訊息傳送的時間 mailMessage.setSentDate(new Date()); MimeMultipart multipart = new MimeMultipart("mixed"); BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<html><body><div>this is a Attachment email.this email has a attachment!</div></body></html>"; messageBodyPart.setContent(htmlText, "text/html; charset=utf-8"); multipart.addBodyPart(messageBodyPart); MimeBodyPart imageBodyPart = new MimeBodyPart(); File imageFile = new File("1_jianggujin.jpg"); DataSource fds = new FileDataSource(imageFile); imageBodyPart.setDataHandler(new DataHandler(fds)); imageBodyPart.setFileName(MimeUtility.encodeWord(imageFile.getName())); multipart.addBodyPart(imageBodyPart); mailMessage.setContent(multipart); // 傳送郵件 Transport.send(mailMessage); } /** * 傳送內嵌圖片和附件郵件 * * @throws Exception */ public void sendImageAndAttachmentMail() throws Exception { Properties pro = System.getProperties(); pro.put("mail.smtp.host", host); pro.put("mail.smtp.port", port); pro.put("mail.smtp.auth", "true"); // 根據郵件會話屬性和密碼驗證器構造一個傳送郵件的session Session sendMailSession = Session.getDefaultInstance(pro, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); // 根據session建立一個郵件訊息 Message mailMessage = new MimeMessage(sendMailSession); // 設定郵件訊息的傳送者 mailMessage.setFrom(new InternetAddress(userName)); // 建立郵件的接收者地址,並設定到郵件訊息中 mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 設定郵件訊息的主題 mailMessage.setSubject("Test Email"); // 設定郵件訊息傳送的時間 mailMessage.setSentDate(new Date()); // 正文 MimeBodyPart text = new MimeBodyPart(); text.setContent("我的頭像:<img src='cid:headImg'>", "text/html;charset=UTF-8"); // 正文圖片 MimeBodyPart image = new MimeBodyPart(); image.setDataHandler( new DataHandler(new FileDataSource("1_jianggujin.jpg"))); image.setContentID("headImg"); // 附件 MimeBodyPart attach = new MimeBodyPart(); DataHandler dh = new DataHandler(new FileDataSource("1_jianggujin.jpg")); attach.setDataHandler(dh); attach.setFileName(MimeUtility.encodeWord(dh.getName())); // 描述關係:正文和圖片 MimeMultipart mp1 = new MimeMultipart(); mp1.addBodyPart(text); mp1.addBodyPart(image); mp1.setSubType("related"); // 正文 MimeBodyPart content = new MimeBodyPart(); content.setContent(mp1); MimeMultipart multipart = new MimeMultipart("mixed"); multipart.addBodyPart(content); multipart.addBodyPart(attach); mailMessage.setContent(multipart); // 傳送郵件 Transport.send(mailMessage); } }

commons-email

使用JAVA Mail我們可以完成郵件的傳送,但是我們可以發現實現過程略顯複雜,比較繁瑣,所以我們可以藉助commons-email簡化傳送郵件的過程,commons-email可以從這裡下載,或在maven中新增如下配置:

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-email</artifactId>
   <version>1.4</version>
</dependency>

示例程式碼:

package com.gujin.mail;

import java.io.File;
import java.util.Date;

import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.SimpleEmail;

public class CommonsEmailTest
{
   private String host = "smtp.126.com";
   private int port = 25;
   private String userName = "";
   private String password = "";
   private String to = "";

   /**
    * 傳送文字郵件
    * 
    * @throws Exception
    */
   public void sendTextMail() throws Exception
   {
      SimpleEmail mail = new SimpleEmail();
      // 設定郵箱伺服器資訊
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 設定密碼驗證器
      mail.setAuthentication(userName, password);
      // 設定郵件傳送者
      mail.setFrom(userName);
      // 設定郵件接收者
      mail.addTo(to);
      // 設定郵件編碼
      mail.setCharset("UTF-8");
      // 設定郵件主題
      mail.setSubject("Test Email");
      // 設定郵件內容
      mail.setMsg("this is a test Text mail");
      // 設定郵件傳送時間
      mail.setSentDate(new Date());
      // 傳送郵件
      mail.send();
   }

   /**
    * 傳送Html郵件
    * 
    * @throws Exception
    */
   public void sendHtmlMail() throws Exception
   {
      HtmlEmail mail = new HtmlEmail();
      // 設定郵箱伺服器資訊
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 設定密碼驗證器
      mail.setAuthentication(userName, password);
      // 設定郵件傳送者
      mail.setFrom(userName);
      // 設定郵件接收者
      mail.addTo(to);
      // 設定郵件編碼
      mail.setCharset("UTF-8");
      // 設定郵件主題
      mail.setSubject("Test Email");
      // 設定郵件內容
      mail.setHtmlMsg(
            "<html><body><img src='http://avatar.csdn.net/A/C/A/1_jianggujin.jpg'/><div>this is a HTML email.</div></body></html>");
      // 設定郵件傳送時間
      mail.setSentDate(new Date());
      // 傳送郵件
      mail.send();
   }

   /**
    * 傳送內嵌圖片郵件
    * 
    * @throws Exception
    */
   public void sendImageMail() throws Exception
   {
      HtmlEmail mail = new HtmlEmail();
      // 設定郵箱伺服器資訊
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 設定密碼驗證器
      mail.setAuthentication(userName, password);
      // 設定郵件傳送者
      mail.setFrom(userName);
      // 設定郵件接收者
      mail.addTo(to);
      // 設定郵件編碼
      mail.setCharset("UTF-8");
      // 設定郵件主題
      mail.setSubject("Test Email");
      mail.embed(new File("1_jianggujin.jpg"), "image");
      // 設定郵件內容
      String htmlText = "<html><body><img src='cid:image'/><div>this is a HTML email.</div></body></html>";
      mail.setHtmlMsg(htmlText);
      // 設定郵件傳送時間
      mail.setSentDate(new Date());
      // 傳送郵件
      mail.send();
   }

   /**
    * 傳送附件郵件
    * 
    * @throws Exception
    */
   public void sendAttachmentMail() throws Exception
   {
      MultiPartEmail mail = new MultiPartEmail();
      // 設定郵箱伺服器資訊
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 設定密碼驗證器
      mail.setAuthentication(userName, password);
      // 設定郵件傳送者
      mail.setFrom(userName);
      // 設定郵件接收者
      mail.addTo(to);
      // 設定郵件編碼
      mail.setCharset("UTF-8");
      // 設定郵件主題
      mail.setSubject("Test Email");

      mail.setMsg("this is a Attachment email.this email has a attachment!");
      // 建立附件
      EmailAttachment attachment = new EmailAttachment();
      attachment.setPath("1_jianggujin.jpg");
      attachment.setDisposition(EmailAttachment.ATTACHMENT);
      attachment.setName("1_jianggujin.jpg");
      mail.attach(attachment);

      // 設定郵件傳送時間
      mail.setSentDate(new Date());
      // 傳送郵件
      mail.send();
   }

   /**
    * 傳送內嵌圖片和附件郵件
    * 
    * @throws Exception
    */
   public void sendImageAndAttachmentMail() throws Exception
   {
      HtmlEmail mail = new HtmlEmail();
      // 設定郵箱伺服器資訊
      mail.setSmtpPort(port);
      mail.setHostName(host);
      // 設定密碼驗證器
      mail.setAuthentication(userName, password);
      // 設定郵件傳送者
      mail.setFrom(userName);
      // 設定郵件接收者
      mail.addTo(to);
      // 設定郵件編碼
      mail.setCharset("UTF-8");
      // 設定郵件主題
      mail.setSubject("Test Email");
      mail.embed(new File("1_jianggujin.jpg"), "image");
      // 設定郵件內容
      String htmlText = "<html><body><img src='cid:image'/><div>this is a HTML email.</div></body></html>";
      mail.setHtmlMsg(htmlText);
      // 建立附件
      EmailAttachment attachment = new EmailAttachment();
      attachment.setPath("1_jianggujin.jpg");
      attachment.setDisposition(EmailAttachment.ATTACHMENT);
      attachment.setName("1_jianggujin.jpg");
      mail.attach(attachment);
      // 設定郵件傳送時間
      mail.setSentDate(new Date());
      // 傳送郵件
      mail.send();
   }
}