java实现发送邮件包含添加附件等(一)

本文介绍了一种使用面向对象方法实现邮件功能的示例,包括邮件信息类、邮件服务器类和邮件发送工具类。重点阐述了如何通过这三个类进行邮件发送操作,包括添加收件人、抄送人、暗送人、邮件主题、内容和附件等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近公司要求做招聘网站,其中有个功能就是邮件功能,我就自己写了个示例,实例需要导入mail.jar。本示例采用了面向对象的思维,首先将邮件功能分为三个类:

邮件信息类(MailInfo)邮件服务器类(MailServer)、邮件发送工具类(MailSender)

邮件信息类主要是针对邮件本身来划分的。具体包括有 邮件主题、邮件内容、邮件附件、 收件人邮箱、抄送人邮箱、暗送人邮箱等。

<span style="font-family:Courier New;"><span style="font-family:Courier New;"><span style="font-family:Courier New;">package com.wugu.zhaopin.mail;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 
* @ClassName: MailInfo
* @Description: 邮件信息类
* @author yangch
*
 */
public class MailInfo implements Serializable{

	private static final long serialVersionUID = 7978358893754871565L;
	
	// 邮件接收者的地址
	private List<Person> toAdress = new ArrayList<Person>();
	// 抄送
	private List<Person> bccAdress = new ArrayList<Person>();
	// 暗送
	private List<Person> ccAdress = new ArrayList<Person>();
	// 邮件主题
	private String subject = "";
	// 邮件的文本内容
	private String content = "";
	// 邮件附件的文件名
	private List<String> atch = new ArrayList<String>();
	
	public List<Person> getToAdress() {
		return toAdress;
	}
	/**
	 * 添加收信人
	 * @param toAdress
	 */
	public void addToAdress(Person toAdress) {
		this.toAdress.add(toAdress);
	}
	/**
	 * 添加暗送人
	 * @param bccAdress
	 */
	public void addBccAdress(Person bccAdress) {
	    this.bccAdress.add(bccAdress);
	}
	/**
	 * 添加抄送人
	 * @param ccAdress
	 */
	public void addCcAdress(Person ccAdress) {
	    this.ccAdress.add(ccAdress);
	}
	/**
	 * 添加附件
	 */
	public void addAtch(String path) {
	    this.atch.add(path);
	}
	public List<Person> getBccAdress() {
		return bccAdress;
	}
	public List<Person> getCcAdress() {
		return ccAdress;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public List<String> getAtch() {
		return atch;
	}
	
	public String listToString(List<Person> list){
	    String str = "";
	    for (Person person : list)
        {
           str += "姓名=" + person.name;
           str += "邮箱地址=" + person.address;
           str += "     ";
        }
	    return str;
	}
	
	/**
	 * 收信人信息
	 * @author Administrator
	 */
	public static class Person implements Serializable{
		/**
		 * 
		 */
		private static final long serialVersionUID = 361815405618703809L;
		
		//姓名
		private String name;
		//地址
		private String address;
		
		public Person(){
		    super();
		}
		
		public Person(String name, String address) {
			super();
			this.name = name;
			this.address = address;
		}
		
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getAddress() {
			return address;
		}
		public void setAddress(String address) {
			this.address = address;
		}
		
	}
}
</span></span></span>

注意实体中添加了addToAdress(Personperson)等接受类型为Person参数的方法,方便添加收件人等信息。


邮件服务器类主要是描述邮件发送者以及邮件服务器信息的实体。它包含的属性有 邮件服务器地址(smtp地址)邮件服务器端口号(默认为25)邮件发送者地址、邮件发送人名称、邮件发送者邮箱密码、邮件服务器是否需要对发送人身份进行验证等字段

<span style="font-family:Courier New;"><span style="font-family:Courier New;"><span style="font-family:Courier New;">/**  
* @Title:  MailServer.java
* @Package com.wugu.mail
* @author yangch
* @date  2014-9-19 
* @version V1.0  
* Update Logs:
* ****************************************************
* Name:
* Date:
* Description:
******************************************************
*/
package com.wugu.mail;

import java.io.Serializable;
import java.util.Properties;

/**
 * @ClassName: MailServer
 * @author yangch
 * @date 2014-9-19 
 *
 */
public class MailServer implements Serializable
{

    private static final long serialVersionUID = 1L;
    
    //邮件服务器地址 smtp地址
    private String serverHost;
    
    //邮件服务器端口号
    private String serverPort = "25";
    
    //邮件服务器名称
    private String serverName;

    //邮件服务器邮箱地址
    private String serverAddress;
    
    //邮件服务器密码
    private String password;
    
    //是否需要身份验证
    private boolean isValidate;
    
    public String getServerHost()
    {
        return serverHost;
    }

    public void setServerHost(String serverHost)
    {
        this.serverHost = serverHost;
    }

    public String getServerPort()
    {
        return serverPort;
    }

    public void setServerPort(String serverPort)
    {
        this.serverPort = serverPort;
    }

    public String getServerName()
    {
        return serverName;
    }

    public void setServerName(String serverName)
    {
        this.serverName = serverName;
    }

    public String getServerAddress()
    {
        return serverAddress;
    }

    public void setServerAddress(String serverAddress)
    {
        this.serverAddress = serverAddress;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    public boolean isValidate()
    {
        return isValidate;
    }

    public void setValidate(boolean isValidate)
    {
        this.isValidate = isValidate;
    }

    public Properties getProperties(){
        Properties p = new Properties();
        p.put("mail.smtp.host", this.serverHost);
        p.put("mail.smtp.port", this.serverPort);
        //这样才能通过验证,注意必须得是字符串”true“或”false“
        p.put("mail.smtp.auth", this.isValidate?"true":"false");
        return p;
    }
    /**
    * <p>Title: </p>
    * <p>Description: </p>
    * @author yangch
    * @param serverHost
    * @param serverPort
    * @param serverName
    * @param serverAddress
    * @param password
    * @param isValidate
    * @param template
    */
    public MailServer(String serverHost, String serverPort, String serverName,
            String serverAddress, String password, boolean isValidate)
    {
        super();
        this.serverHost = serverHost;
        this.serverPort = serverPort;
        this.serverName = serverName;
        this.serverAddress = serverAddress;
        this.password = password;
        this.isValidate = isValidate;
    }
}</span></span></span>

邮件发送工具类此类是发送邮件的工具类,封装了一些发送邮件需要用到的方法,如设置收件人、设置抄送人等。

<span style="font-family:Courier New;"></pre><pre name="code" class="java"><span style="font-family:Courier New;">/**  
* @Title:  MailSender.java
* @Package com.wugu.mail
* @Description: TODO(用一句话描述该文件做什么)
* @author yangch
* @date  2014-9-19 
* @version V1.0  
* Update Logs:
* ****************************************************
* Name:
* Date:
* Description:
******************************************************
*/
package com.wugu.mail;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
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;

import com.wugu.mail.MailInfo.Person;

/**
 * @ClassName: MailSender
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author yangch
 * @date 2014-9-19 
 *
 */
public class MailSender implements Serializable
{

    private static final long serialVersionUID = 1L;
    private static final Logger log = Logger.getLogger(MailSender.class.getName());
    private MailServer mailServer;
    public MailSender(MailServer mailServer){
        this.mailServer = mailServer;
    }
    
    //身份验证器
    class MailAuth extends Authenticator{
        private String username;
        private String password;
        public MailAuth(String username, String password){
            this.username = username;
            this.password = password;
        }
        public MailAuth(){
            
        }
        @Override
        protected PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(username, password);
        }
    }
    
    //获取对应的收件人
    public Address[] getAddressArr(List<Person> list) throws UnsupportedEncodingException, AddressException{
        Address[] to = new Address[list.size()];
        for(int i = 0; i < to.length; i++){
            Person person = list.get(i);
            if(null == person.getName()){
                to[i] = new InternetAddress(person.getAddress());
            }else{
                to[i] = new InternetAddress(person.getAddress(), MimeUtility.encodeText(person.getName(), MimeUtility.mimeCharset("utf-8"), null));
            }
        }
        return to;
    }
    
    //设置收件人信息
    public void setRecipients_To(Message message, MailInfo mailInfo) throws Exception{
        List<MailInfo.Person> list = mailInfo.getToAdress();
        if(null == list || list.isEmpty()){
            throw new Exception("toAddress can not be null");
        }
        Address[] to = getAddressArr(mailInfo.getToAdress());
        message.setRecipients(Message.RecipientType.TO, to);
    }
    
    //设置抄送人地址
    public void setRecipients_CC(Message message, MailInfo mailInfo) throws Exception{
        List<Person> list = mailInfo.getCcAddress();
        if(null != list && list.size() > 0){
            Address[] cc = getAddressArr(list);
            message.setRecipients(Message.RecipientType.CC, cc);
        }
    }
    
    //设置暗送地址
    public void setRecipients_BCC(Message message, MailInfo mailInfo) throws MessagingException, UnsupportedEncodingException{
        List<Person> list = mailInfo.getBccAddress();
        if(null != list && list.size() > 0){
            Address[] bcc = getAddressArr(list);
            message.setRecipients(Message.RecipientType.BCC, bcc);
        }
    }
   
    //设置附件和内容
    public void setHTMLPart(Message message, MailInfo mailInfo) throws MessagingException, UnsupportedEncodingException{
        Multipart multi = new MimeMultipart();
        List<String> list = mailInfo.getAttch();
        
        //设置附件
        for(String attch:list){
            MimeBodyPart body = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(attch);
            body.setDataHandler(new DataHandler(fds));
            body.setFileName(MimeUtility.encodeWord(fds.getName(), "GB2312", null));
            multi.addBodyPart(body);
        }
        //设置内容
        MimeBodyPart textBody = new MimeBodyPart();
        textBody.setContent(mailInfo.getContent(), "text/html;charset=utf-8");
        multi.addBodyPart(textBody);
        
        // 将MiniMultipart对象设置为邮件内容
        message.setContent(multi);
        message.setSentDate(new Date());
    }
    
    /**
     * 
      * @Title: sendMail_in
      * @Description: 邮件工具类
      * @author yangch
      * @date 2014-9-22 
      * @param info
      * @throws Exception
      * @throws
     */
    public void sendMail_in(MailInfo info) throws Exception{
        Properties prop = this.mailServer.getProperties();
        Authenticator auth = new MailAuth(mailServer.getServerAddress(), mailServer.getPassword());
        Session session = Session.getDefaultInstance(prop, auth);
        session.setDebug(true);
        Message message = new MimeMessage(session);
        log.info("--------开始发送邮件---------");
        message.setSubject(MimeUtility.encodeText(info.getSubject(), MimeUtility.mimeCharset("utf-8"), null));
        log.info("邮件主题为:"+info.getSubject());
        
        log.info("发送人地址:"+mailServer.getServerAddress());
        Address from = new InternetAddress(mailServer.getServerAddress(), MimeUtility.encodeText(mailServer.getServerAddress(), MimeUtility.mimeCharset("utf-8"), null));
        message.setFrom(from);
        
        log.info("收件人地址"+info.listToString(info.getToAdress()));
        setRecipients_To(message, info);
        
        //设置抄送
        setRecipients_CC(message, info);
        log.info("抄送人地址"+info.listToString(info.getCcAddress()));
        
        //设置暗送
        setRecipients_BCC(message, info);
        log.info("暗送人地址"+info.listToString(info.getBccAddress()));
        
        //设置附件和内容
        setHTMLPart(message, info);
        
        //发送邮件
        Transport.send(message);
        log.info("-------------发送成功--------------");
    }
    
    /**
     * 
      * @Title: sendMail
      * @Description: 邮件发送前进行必填项的检查
      * @author yangch
      * @date 2014-9-22 
      * @param info
      * @throws Exception
      * @throws
     */
    public void sendMail(MailInfo info) throws Exception{
        if(mailServer == null || mailServer.getServerHost() == null || mailServer.getServerAddress() == null
                || mailServer.getServerPort() == null || mailServer.getPassword() == null){
            throw new Exception("邮件服务器为空或者配置不全");
        }
        sendMail_in(info);
    }
    
    //测试方法
    public static void main(String[] args) throws Exception
    {
        MailInfo mail = new MailInfo();
        //设置附件
        mail.addAttch("D:\\work\\ARCH4系统架构设计说明书.doc");
        //设置内容
        mail.setContent("<html><head><h1>我是测试邮件。。。。。</h1></head></html>");
        mail.setSubject("Hello Mail !!!");
        //设置收件人地址
        mail.addToAddress(new Person("洋洋", "991622230@qq.com"));
        //设置
        MailServer server = new MailServer("smtp.exmail.qq.com", "25", "吾谷人才", "你的邮箱@wugu.com.cn", "您的密码", true);
        MailSender sender = new MailSender(server);
        sender.sendMail(mail);
    }
    public MailServer getMailServer()
    {
        return mailServer;
    }
    public void setMailServer(MailServer mailServer)
    {
        this.mailServer = mailServer;
    }
    
}
</span></span>



将测试数据中的附件地址及邮箱和密码改为自己的邮箱密码,即可发送邮件了。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值