javamail的总结

  Javamail邮件发送的总结:
    首先需要导入的jar包:两个分别是mail.jar和activation.jar。

邮件大致可以分三种:纯文本邮件、含有其他数据的文本邮件、含有附件的邮件。
下面我做了两个实验,源代码如下:
案例一
发送html形式的邮件:RemindMail.java
  package mocha.jlcm.mail.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
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 mocha.jlcm.fore.dao.OvertimeTaskDao;

/**
* @author panyt 2011-11-01
*
* 发送html形式的邮件,
*/
public class RemindMail
{
    //邮箱服务器
    private String host;
    //发件人邮箱用户名
    private String username;
    //邮箱密码
    private String password ;
    //邮件标题名
    private String mail_head_name;
    //邮件标题名内容
    private String mail_head_value ;
    //收件人邮箱
    private String mail_to;
    //发件人邮箱
    private String mail_from;

    //信件标题
    private String mail_subject;
    //信件内容
    private String mailBody;
    //发件人的名称
    private String personalName;
    Properties properties = new Properties();
   
    OvertimeTaskDao dao;
public void setDao(OvertimeTaskDao dao) {
this.dao = dao;
}
   
    public RemindMail()
    {
     try {
properties.load(getClass().getResourceAsStream("/jlmail.properties"));
} catch (IOException e) {
e.printStackTrace();
}
   
    }
   
    /**
     * 读取配置文件jlemail.properties对应的值
     */
    public void getPropertiesValue(){
    host = properties.getProperty("host");
    username = properties.getProperty("username");
    password = properties.getProperty("password");
    mail_head_name = properties.getProperty("mail_head_name");
    mail_head_value = properties.getProperty("mail_head_value");
    mail_to = properties.getProperty("mail_to");
    mail_from = properties.getProperty("mail_from");
    mail_subject = properties.getProperty("mail_subject");
    //mail_body = properties.getProperty("mail_body");
    personalName = properties.getProperty("personalName");
    }

    /**
     * 此段代码用来发送普通电子邮件
     *
     * @deptId 责任部门id
     */
    public void send(String deptId) throws Exception
    {
       
        try
        {
            Properties props = new Properties(); // 获取系统环境
            Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
            this.getPropertiesValue();
          // String manger = dao.getDeptName(deptId);
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props, auth);
           
            mailBody = this.getMailBody();
         // 新建一个MimeMultipart对象用来存放BodyPart对象(事实上可以存放多个)
            MimeMultipart mm = new MimeMultipart();
            // 新建一个存放信件内容的BodyPart对象
            BodyPart mdp = new MimeBodyPart();
            // 给BodyPart对象设置内容和格式/编码方式
            mdp.setContent(mailBody, "text/html;charset=utf-8");
            mm.setSubType("related");

            mm.addBodyPart(mdp);
         // 设置session,和邮件服务器进行通讯。
            MimeMessage message = new MimeMessage(session);
            message.setContent(mm); // 设置邮件格式
            message.setSubject(mail_subject); // 设置邮件主题
            //message.setText(mail_body); // 设置邮件正文
            message.saveChanges();
            message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题
            message.setSentDate(new Date()); // 设置邮件发送日期
            Address address = new InternetAddress(mail_from, personalName);
            message.setFrom(address); // 设置邮件发送者的地址
           // 设置邮件接收方的地址
          //  Address toAddress = new InternetAddress(manger+mail_to);
            Address toAddress = new InternetAddress(mail_to);
            message.addRecipient(Message.RecipientType.TO, toAddress);
            Transport.send(message); // 发送邮件
            System.out.println("send ok!!!!!"+mail_to);
        } catch (Exception ex)
        {
            ex.printStackTrace();
            throw new Exception(ex.getMessage());
        }
    }

     /**
      * 邮件内容
     * @return
     */
    public String getMailBody(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
     StringBuffer mail_body=new StringBuffer();
     mail_body.append("<html><head><title></title></head><body>");
     mail_body.append("<div>");
     mail_body.append("<div>");
     mail_body.append("XXX,您好!<br>");
     mail_body.append("&emsp;&emsp;根据XX系统统计,
                     请及时处理任务工作。具体待办任务<br>");
     mail_body.append("&emsp;如下:<br>");
     mail_body.append("<table  border='1' cellpadding='1' bordercolor='#000000' cellspacing='0' width='800'>");
     mail_body.append("<tr align='center'>");
     mail_body.append("<td>流程类型</td><td>所属流程</td><td>超时任务</td><td>状态</td><td>责任部门</td><td>预计处理时限(天)</td><td>实际已用时间(天)</td>");
     mail_body.append("</tr>");
     mail_body.append("<tr align='center'>");
     mail_body.append("<td>"+1+"</td>");
     mail_body.append("<td>"+2+"</td>");
     mail_body.append("<td>"+3+"</td>");
     mail_body.append("<td>"+4+"</td>");
     mail_body.append("<td>"+5+"</td>");
     mail_body.append("<td>"+6+"</td>");
     mail_body.append("<td>"+7+"</td>");
     mail_body.append("</tr>");
     mail_body.append("<table>");
     mail_body.append("<br><br><br>");
     mail_body.append("</div>");
     mail_body.append("<div>");
     mail_body.append("&nbsp;&nbsp;&nbsp;&nbsp;祝工作顺利!<br><br>");
     mail_body.append("PS:此邮件通过系统自动发送,请勿回复!<br>");
     mail_body.append("</div>");
     mail_body.append("<br><br>");
     mail_body.append("<div align=\"right\" style='width:800'>XXX(发送催办邮件人员姓名)</div><br>");
     mail_body.append("<div align=\"right\" style='width:800'>"+sdf.format(new Date())+"</div>");
     mail_body.append("</div>");
     mail_body.append("</body></html>");
    
     return  mail_body.toString();
     }
   
    /**
     * 用来进行服务器对用户的认证
     */
    public class Email_Autherticator extends Authenticator
    {
        public Email_Autherticator()
        {
            super();
        }

        public Email_Autherticator(String user, String pwd)
        {
            super();
            username = user;
            password = pwd;
        }

        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username, password);
        }
    }

    public static void main(String[] args)
    {
        RemindMail sendmail = new RemindMail();
        try
        {
            sendmail.send("");
        } catch (Exception ex)
        {
        }
    }

}
配置的属性文件:jlmail.properties

  #邮箱服务器
host = smtp.163.com
#发件人邮箱用户名
username = ***@163.com
# 邮箱密码
password = ********
#邮件标题名
mail_head_name = head mail
#邮件标题名内容
mail_head_value = head mail
#收件人邮箱
mail_to = *****@126.com
#发件人邮箱
mail_from = [email protected]
#信件标题
mail_subject = 提醒邮件
#信件内容
mailBody = 注意未办信息
#发件人的名称
personalName = XX领导
这项目已经验证了,可以进行信息的发送。

案例二:
带附件的邮件发送:

package com.mocha;  
 
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
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;

/**
* 准备好两个邮箱帐号 
* 这两个邮箱已经存在 可直接登录
*/
 
/** *//** 
* 发送普通邮件(带有附件),接受普通邮件 发送带有附件的邮件,接收带有附件的邮件 发送html形式的邮件,接受html形式的邮件 发送带有图片的邮件等做了一个总结。 
*/ 
public class MailMultiTest  
{  
    // 邮箱服务器  
    private String host = "smtp.163.com";  
    // 这个是你的邮箱用户名  
    private String username = "*****";  
    // 你的邮箱密码  
    private String password = "*****";  
      
    private String mail_head_name = "this is head of this mail";  
 
    private String mail_head_value = "this is head of this mail";  
 
    private String mail_to = "***@163.com";  
 
    private String mail_from = "*****@163.com";  
 
    private String mail_subject = "this is the subject of this test mail";  
 
    private String mail_body = "this is the mail_body of this test mail";  
 
    private String personalName = "发件人姓名";  
 
    public MailMultiTest()  
    {  
    }  
 
    /** *//** 
     * 此段代码用来发送普通电子邮件 
     */ 
    public void send() throws Exception  
    {  
        try 
        {  
            Properties props = new Properties(); // 获取系统环境  
            Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证  
            props.put("mail.smtp.host", host);  
            props.put("mail.smtp.auth", "true");  
            Session session = Session.getDefaultInstance(props, auth);  
            // 设置session,和邮件服务器进行通讯。  
            MimeMessage message = new MimeMessage(session);  
            // message.setContent("foobar, "application/x-foobar"); // 设置邮件格式  
            message.setSubject(mail_subject); // 设置邮件主题  
           // message.setText(mail_body); // 设置邮件正文  
            message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题  
            message.setSentDate(new Date()); // 设置邮件发送日期  
            Address address = new InternetAddress(mail_from, personalName);  
            message.setFrom(address); // 设置邮件发送者的地址  
            Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址  
            message.addRecipient(Message.RecipientType.TO, toAddress); 
           
            String  attch1 = "G:/1.txt";
            String attch2 = "G:/2.txt";
           
            Multipart multipart = new MimeMultipart();
           
            //加入文本内容
            MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
            mimeBodyPart1.setText("how are you !") ;
            multipart.addBodyPart(mimeBodyPart1) ;
           
            //加入第一个附件
            MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(attch1);
            mimeBodyPart2.setDataHandler(new DataHandler(fds)) ;
            mimeBodyPart2.setDisposition(Part.ATTACHMENT) ;
            mimeBodyPart2.setFileName(fds.getName()) ;
            multipart.addBodyPart(mimeBodyPart2) ;
           
            //加入第二个附件
            MimeBodyPart mimeBodyPart3 = new MimeBodyPart();
             fds = new FileDataSource(attch2);
            mimeBodyPart3.setDataHandler(new DataHandler(fds)) ;
            mimeBodyPart3.setDisposition(Part.INLINE) ;
            mimeBodyPart3.setFileName(fds.getName()) ;
            multipart.addBodyPart(mimeBodyPart3) ;
           
            message.setContent(multipart) ;
           
            Transport.send(message); // 发送邮件  
            System.out.println("send ok!");  
        } catch (Exception ex)  
        {  
            ex.printStackTrace();  
            throw new Exception(ex.getMessage());  
        }  
    }  
 
    /** *//** 
     * 用来进行服务器对用户的认证 
     */ 
    public class Email_Autherticator extends Authenticator  
    {  
        public Email_Autherticator()  
        {  
            super();  
        }  
 
        public Email_Autherticator(String user, String pwd)  
        {  
            super();  
            username = user;  
            password = pwd;  
        }  
 
        public PasswordAuthentication getPasswordAuthentication()  
        {  
            return new PasswordAuthentication(username, password);  
        }  
    }  
 
    public static void main(String[] args)  
    {  
        MailMultiTest sendmail = new MailMultiTest();  
        try 
        {  
            sendmail.send();  
        } catch (Exception ex)  
        {  
        }  
    }  
 
}
这项目已经验证了,可以进行信息的发送。

你可能感兴趣的:(java,},{,())