JAVAMail发送邮件

Author:Rockay(刘其超,刘涛)

Page:http://www.cnblogs.com/Rockay
Email:[email protected]

注:有部分是参考网上资料。

接上次smtp邮件发送功能,这次用的是JAVAMail, 运行此程序还需三个Java包:mail.jar,activation.jar和htmlparser.jar。 

下面介绍一下JAVAMail中一些基础类,信息如下:

Session类
Session类定义了一个基本的邮件会话。通过该会话可让别的工作顺利执行。Session对象利用java.util.Properties对象获取诸如邮件服务器、用户名、密码等信息,以及其他可在整个应用程序中共享的信息。

Message类
创建要发送的消息。

Address类
一旦创建了会话和消息,并为消息填充了内容,就需要用Address类为您的信件标上地址了。

Authenticator类
与java.net类一样,JavaMail API可以利用Authenticator(验证程序)类通过用户名和密码来访问受保护的资源。

Transport类
发送消息的最后一步操作是使用Transport类。该类使用特定于协议(通常是SMTP)的语言来发送消息。

 

代码示例如下:

抽象类:SendMail .JAVA

package gxa.sf.rockay;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
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.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
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 org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.ParserException;

/**
 * 邮件发送组件,具体的使用方法参照该类的main方法
 * @author Rockay(刘其超,刘涛)
 */
public abstract class SendMail extends Authenticator {

 public String username = null; // 邮件发送帐号用户名

 public String userpasswd = null; // 邮件发送帐号用户口令

 public BodyPart messageBodyPart = null;

 public Multipart multipart = new MimeMultipart("related");

 public MimeMessage mailMessage = null;

 public Session mailSession = null;

 public Properties mailProperties = System.getProperties();

 public InternetAddress mailFromAddress = null;

 public InternetAddress mailToAddress = null;

 public Authenticator authenticator = null;

 public String mailSubject = "";

 public Date mailSendDate = null;

 /**
  * 构造函数
  *
  * @param smtpHost
  * @param username
  * @param password
  */
 public SendMail(String smtpHost, String username, String password) {
  this.username = username;
  this.userpasswd = password;
  mailProperties.put("mail.smtp.host", smtpHost);
  mailProperties.put("mail.smtp.auth", "true"); // 设置smtp认证,很关键的一句
  mailSession = Session.getDefaultInstance(mailProperties, this);
  mailMessage = new MimeMessage(mailSession);
  messageBodyPart = new MimeBodyPart();
 }

 /**
  * 构造一个纯文本邮件发送实例
  *
  * @param smtpHost
  * @param username
  * @param password
  * @return
  */
 public static SendMail getTextMailSender(String smtpHost, String username,
   String password) {
  return new SendMail(smtpHost, username, password) {
   public void setMailContent(String mailContent)
     throws MessagingException {
    messageBodyPart.setText(mailContent);
    multipart.addBodyPart(messageBodyPart);
   }
  };
 }

 /**
  * 构造一个超文本邮件发送实例
  *
  * @param smtpHost
  * @param username
  * @param password
  * @return
  */
 public static SendMail getHtmlMailSender(String smtpHost, String username,
   String password) {
  return new SendMail(smtpHost, username, password) {
   private ArrayList arrayList1 = new ArrayList();

   private ArrayList arrayList2 = new ArrayList();

   public void setMailContent(String mailContent)
     throws MessagingException {
    String htmlContent = getContent("<img src=", mailContent);
    messageBodyPart.setContent(htmlContent,
      "text/html;charset=GB2312");
    multipart.addBodyPart(messageBodyPart);
    // 调用处理html文件中的图片方法
    processHtmlImage(mailContent);
   }

   // 处理html页面上的图片方法如下:
   private void processHtmlImage(String mailContent)
     throws MessagingException {
    for (int i = 0; i < arrayList1.size(); i++) {
     messageBodyPart = new MimeBodyPart();
     DataSource source = new FileDataSource((String) arrayList1
       .get(i));
     messageBodyPart.setDataHandler(new DataHandler(source));
     String contentId = "<" + (String) arrayList2.get(i) + ">";
     messageBodyPart.setHeader("Content-ID", contentId);
     messageBodyPart.setFileName((String) arrayList1.get(i));
     multipart.addBodyPart(messageBodyPart);
    }
   }

   // 处理要发送的html文件,主要是针对html文件中的图片
   private String getContent(String searchString, String mailContent) {
    try {
     Parser parser = Parser.createParser(new String(mailContent
       .getBytes(), ISO8859_1));
     Node[] images = parser
       .extractAllNodesThatAre(ImageTag.class);
     for (int i = 0; i < images.length; i++) {
      ImageTag imgTag = (ImageTag) images[i];
      if (!imgTag.getImageURL().toLowerCase().startsWith(
        "http://"))
       arrayList1.add(imgTag.getImageURL());
     }
    } catch (UnsupportedEncodingException e1) {
    } catch (ParserException e) {
    }
    String afterReplaceStr = mailContent;
    // 在html文件中用"cid:"+Content-ID来替换原来的图片链接
    for (int m = 0; m < arrayList1.size(); m++) {
     arrayList2.add(createRandomStr());
     String addString = "cid:" + (String) arrayList2.get(m);
     afterReplaceStr = mailContent.replaceAll(
       (String) arrayList1.get(m), addString);
    }
    return afterReplaceStr;
   }

   // 产生一个随机字符串,为了给图片设定Content-ID值
   private String createRandomStr() {
    char[] randomChar = new char[8];
    for (int i = 0; i < 8; i++) {
     randomChar[i] = (char) (Math.random() * 26 + 'a');
    }
    String replaceStr = new String(randomChar);
    return replaceStr;
   }

   private final static String ISO8859_1 = "8859_1";
  };
 }

 /**
  * 用于实现邮件发送用户验证
  *
  * @see javax.mail.Authenticator#getPasswordAuthentication
  */
 public PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication(username, userpasswd);
 }

 /**
  * 设置邮件标题
  *
  * @param mailSubject
  * @throws MessagingException
  */
 public void setSubject(String mailSubject) throws MessagingException {
  this.mailSubject = mailSubject;
  mailMessage.setSubject(mailSubject);
 }

 /**
  * 所有子类都需要实现的抽象方法,为了支持不同的邮件类型
  *
  * @param mailContent
  * @throws MessagingException
  */
 public abstract void setMailContent(String mailContent)
   throws MessagingException;

 /**
  * 设置邮件发送日期
  *
  * @param sendDate
  * @throws MessagingException
  */
 public void setSendDate(Date sendDate) throws MessagingException {
  this.mailSendDate = sendDate;
  mailMessage.setSentDate(sendDate);
 }

 /**
  * 设置邮件发送附件
  *
  * @param attachmentName
  * @throws MessagingException
  */
 public void setAttachments(String attachmentName) throws MessagingException {
  messageBodyPart = new MimeBodyPart();
  DataSource source = new FileDataSource(attachmentName);
  messageBodyPart.setDataHandler(new DataHandler(source));
  int index = attachmentName.lastIndexOf(File.separator);
  String attachmentRealName = attachmentName.substring(index + 1);
  messageBodyPart.setFileName(attachmentRealName);
  multipart.addBodyPart(messageBodyPart);
 }

 /**
  * 设置发件人地址
  *
  * @param mailFrom
  * @throws MessagingException
  */
 public void setMailFrom(String mailFrom) throws MessagingException {
  mailFromAddress = new InternetAddress(mailFrom);
  mailMessage.setFrom(mailFromAddress);
 }

 /**
  * 设置收件人地址,收件人类型为to,cc,bcc(大小写不限)
  *
  * @param mailTo
  *            邮件接收者地址
  * @param mailType
  *            值为to,cc,bcc
  * @author Liudong
  */
 public void setMailTo(String[] mailTo, String mailType) throws Exception {
  for (int i = 0; i < mailTo.length; i++) {
   mailToAddress = new InternetAddress(mailTo[i]);
   if (mailType.equalsIgnoreCase("to")) {
    mailMessage.addRecipient(Message.RecipientType.TO,
      mailToAddress);
   } else if (mailType.equalsIgnoreCase("cc")) {
    mailMessage.addRecipient(Message.RecipientType.CC,
      mailToAddress);
   } else if (mailType.equalsIgnoreCase("bcc")) {
    mailMessage.addRecipient(Message.RecipientType.BCC,
      mailToAddress);
   } else {
    throw new Exception("Unknown mailType: " + mailType + "!");
   }
  }
 }

 /**
  * 开始发送邮件
  *
  * @throws MessagingException
  * @throws SendFailedException
  */
 public void sendMail() throws MessagingException, SendFailedException {
  if (mailToAddress == null)
   throw new MessagingException("请你必须你填写收件人地址!");
  mailMessage.setContent(multipart);
  Transport.send(mailMessage);
 }

}

 

 

子类继承抽象类:

package gxa.sf.rockay;

/**
 * 继承SendMail类
 * @author Rockay(刘其超,刘涛)
 */

import java.util.Date;

import javax.mail.MessagingException;

public class LTMail extends SendMail {
 public LTMail(String mailHost, String username, String password) {
  super(mailHost, username, password);
  // TODO 自动生成构造函数存根
 }
 
 public void setMailContent(String mailContent) throws MessagingException {
  // TODO 自动生成方法存根
  
 }
 
 public String Send(String mailFrom, String mailHost,String mailUser,String mailPassword,String[] toAddress,String[] ccAddress,String[] bcAddress,String title,String content,boolean flag)
 {
  SendMail sendmail;
        //使用超文本格式发送邮件
  if(flag){
    sendmail = SendMail.getHtmlMailSender(mailHost, mailUser,mailPassword);
        }
        else{
          sendmail = SendMail.getTextMailSender(mailHost, mailUser,mailPassword);
        }
       
        //使用纯文本格式发送邮件
        //
        try {
            sendmail.setSubject(title);
            sendmail.setSendDate(new Date());
           
            sendmail.setMailContent(content); //
            //sendmail.setAttachments("E:\\ConList.exe");//文章附件
            sendmail.setMailFrom(mailFrom);//显示谁发送的
            if(toAddress.length>=1)
             sendmail.setMailTo(toAddress, "to");//cc抄送,bcc 暗送
            if(ccAddress.length>=1)
             sendmail.setMailTo(ccAddress, "cc");//设置抄送给...
            if(bcAddress.length>=1)
             sendmail.setMailTo(bcAddress, "bcc");
            //开始发送邮件
            System.out.println("正在发送邮件,请稍候.......");
            sendmail.sendMail();
            System.out.println("邮件发送成功");
            return "邮件发送成功!!!";
        } catch (Exception ex) {
         return "邮件发送失败:"+ex.getMessage() ;
        }
 }
 }

 

index.html页面

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>超超邮件系统</title>
</head>
<body bgcolor="#ffffff">
<form name="form1"   action="send.jsp" method="POST" >
<h1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;欢迎使用超超邮件系统</h1>
 <table width="75%" border="0" align="center">
   <tr>
     <td colspan="3">请输入所有信息以发送邮件</td>
   </tr>
   <tr>
    <td>
    <input type='radio' name='radio' value='纯文本' checked="checked">  
    <input type='radio' name='radio' value='HTML'>
    </td>
   <tr>
     <td>邮件服务器:</td>
            <td><input name="mailserver" type="text" size="40" value="smtp.163.com"/></td>
            <td>&nbsp;</td>
   </tr>
   <tr>
     <td>邮箱账号:</td>
            <td><input name="mailID" type="text" size="40" value="luqichao178"/></td>
            <td>&nbsp;</td>
   </tr>
   <tr>
     <td>邮箱密码:</td>
            <td><input name="mailpwd" type="password" size="40" value=""/></td>
            <td>&nbsp;</td>
   </tr>
     
      <tr>
            <td>发件人:</td>
            <td><input name="mailfrom" type="text" size="40" value=""></td>
            <td>&nbsp;</td>
   </tr>
      <tr>
            <td>收件人:</td>
            <td><input name="mailto" type="text" size="40" value=""/></td>
            <td>&nbsp;</td>
   </tr>
   <tr>
            <td>抄送:</td>
            <td><input name="mailcopy" type="text" size="40" value=""/></td>
            <td>&nbsp;</td>
   </tr>
   <tr>
            <td>暗抄:</td>
            <td><input name="mailbc" type="text" size="40" value=""/></td>
            <td>&nbsp;</td>
   </tr>
      <tr>
            <td>主题:</td>
            <td><input name="subject" type="text" size="40" value=""/></td>
            <td>&nbsp;</td>
   </tr>
      <tr>
            <td>内容:</td>
            <td>
            <textarea name="content" rows="20" cols="100">
            <H1>Hello Rockay:</H1>
            <img src="G:/Software Park Photos/cs.gif"/>
            </textarea>
            </td>
            <td>&nbsp;</td>
   </tr>
     </table>
      <p>&nbsp;<p>
<center><input type="submit" name="提交"/>
</form>
</body>
</html>

 

send.jsp页面

 <%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>
<%@ page import= "gxa.sf.rockay.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Insert title here</title>
</head>
<body>
<%
 String mailFrom =new String(request.getParameter("mailfrom").getBytes("ISO-8859-1"),"GB2312");   //发送者,防止乱码
 String mailHost = new String(request.getParameter("mailserver").getBytes("ISO-8859-1"),"GB2312"); //发送邮件服务器地址
    String mailUser = new String(request.getParameter("mailID").getBytes("ISO-8859-1"),"GB2312");   //发送邮件服务器的用户帐号
    String mailPassword = request.getParameter("mailpwd");   //发送邮件服务器的用户密码
    String ToAddresses=request.getParameter("mailto");
   
    boolean flag;
    String type = request.getParameter("radio");
    if(type.equals("HTML")){
    flag=true;
    }else{
    flag = false;
    }
    String[] toAddress = ToAddresses.split(";");
   
    String CopyAddresses=request.getParameter("mailcopy");
    String[] ccAddress=CopyAddresses.split(";");
   
    String BcAddresses=request.getParameter("mailbc");
    String[] bcAddress=BcAddresses.split(";");
   
    String title=new String(request.getParameter("subject").getBytes("ISO-8859-1"),"GB2312");
    String content=new String(request.getParameter("content").getBytes("ISO-8859-1"),"GB2312");
   
 LTMail ltmail = new LTMail(mailHost,mailUser,mailPassword);
 String message = "";
 message = ltmail.Send(mailFrom,mailHost,mailUser,mailPassword,toAddress,ccAddress,bcAddress,title,content,flag);
 out.println("<center><h1>"+message+"</h1>");
 
 %>
</body>
</html>

 好了,代码太多,可能看起来有点痛苦,有需要的可以EMAIL:[email protected]

你可能感兴趣的:(javamail)