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();
   }
}

你可能感兴趣的:(java,邮件,email,commons)