JavaMail 学习

JavaMail 是 java 的扩展类库包,利用其可以创建发送和接收电子邮件的应用。JavaMail 支持 SMTP、POP、IMAP 等协议。关于这些协议的内容,请参考相关的知识。毕竟是个网络满天飞的世界,google 和 baidu 都有最权威的答案。给出 3 个文件,实现了使用 SMTP 协议发送电子邮件及附件。

(1) Mail.java 文件。

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* Mail 类表示要发送的一封邮件。
* @author dingli
*/
public class Mail
{
private String subject = null;
private String from = null;
private List sendTo = null;
private List carbonCopy = null;
private List blindCarbonCopy = null;
private List attachment = null;
private String content = null;
private Date sendDate = null;

/**
* Mail 的默认构造方法。
*/
public Mail()
{
this.sendTo = new ArrayList();
this.carbonCopy = new ArrayList();
this.blindCarbonCopy = new ArrayList();
this.attachment = new ArrayList();
this.sendDate = new Date(System.currentTimeMillis());
}

/**
* 获取邮件附件所在本地路径列表。
* @return 邮件附件所在本地路径列表。
*/
public List getAttachment()
{
return attachment;
}

/**
* 设置邮件附件所在本地路径。
* @param path 邮件附件所在本地路径。
*/
public void setAttachment(String path)
{
this.attachment.add(path);
}

/**
* 获取邮件暗送人列表。
* @return 邮件暗送人列表。
*/
public List getBlindCarbonCopy()
{
return blindCarbonCopy;
}

/**
* 设置邮件暗送人列表。
* @param blindCarbonCopy 邮件暗送人列表。
*/
public void setBlindCarbonCopy(List blindCarbonCopy)
{
this.blindCarbonCopy = blindCarbonCopy;
}

/**
* 获取邮件抄送人列表。
* @return 邮件抄送人列表。
*/
public List getCarbonCopy()
{
return carbonCopy;
}

/**
* 设置邮件抄送人列表。
* @param carbonCopy 邮件抄送人列表。
*/
public void setCarbonCopy(List carbonCopy)
{
this.carbonCopy = carbonCopy;
}

/**
* 获取邮件收件人列表。
* @return 邮件收件人列表。
*/
public List getSendTo()
{
return sendTo;
}

/**
* 设置邮件收件人列表。
* @param sendTo 邮件收件人列表。
*/
public void setSendTo(List sendTo)
{
this.sendTo = sendTo;
}

/**
* 获取邮件内容。
* @return 邮件内容。
*/
public String getContent()
{
return content;
}

/**
* 设置邮件内容。
* @param content 邮件内容。
*/
public void setContent(String content)
{
this.content = content;
}

/**
* 获取邮件发件人。
* @return 邮件发件人。
*/
public String getFrom()
{
return from;
}

/**
* 设置邮件发件人。
* @param from 邮件发件人。
*/
public void setFrom(String from)
{
this.from = from;
}

/**
* 获取邮件发送日期。
* @return 邮件发送日期。
*/
public Date getSendDate()
{
return sendDate;
}

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

/**
* 获取邮件主题。
* @return 邮件主题。
*/
public String getSubject()
{
return subject;
}

/**
* 设置邮件主题。
* @param subject 邮件主题。
*/
public void setSubject(String subject)
{
this.subject = subject;
}
}

(2) MailConfig.java 文件。

/**
* MailConfig 表示发送或接收邮件的配置信息。
* @author Dingli.
*/
public class MailConfig
{
private String protocol = null;
private String server = null;
private String user = null;
private String password = null;
private int port = 0;
private boolean debug;

/**
* MailConfig 的默认构造方法。
*/
public MailConfig()
{
this.protocol = "smtp";
this.port = 25;
this.debug = false;
}

/**
* 获取是否显示邮件操作的调试信息。
* @return 是否显示邮件操作的调试信息。
*/
public boolean isDebug()
{
return debug;
}

/**
* 设置是否显示邮件操作的调试信息。
* @param debug 是否显示邮件操作的调试信息。
*/
public void setDebug(boolean debug)
{
this.debug = debug;
}

/**
* 获取登录密码。
* @return 登录密码。
*/
public String getPassword()
{
return password;
}

/**
* 设置登录密码。
* @param password 登录密码。
*/
public void setPassword(String password)
{
this.password = password;
}

/**
* 获取登录用户名。
* @return 登录用户名。
*/
public String getUser()
{
return user;
}

/**
* 设置登录用户名。
* @param user 登录用户名。
*/
public void setUser(String user)
{
this.user = user;
}

/**
* 获取邮件服务器端口。
* @return 邮件服务器端口。
*/
public int getPort()
{
return port;
}

/**
* 设置邮件服务器端口。
* @param port 邮件服务器端口。
*/
public void setPort(int port)
{
this.port = port;
}

/**
* 获取发送或接收邮件的协议。
* @return 发送或接收邮件的协议。
*/
public String getProtocol()
{
return protocol;
}

/**
* 设置发送或接收邮件的协议。
* @param protocol 发送或接收邮件的协议。
*/
public void setProtocol(String protocol)
{
this.protocol = protocol;
}

/**
* 获取邮件服务器。
* @return 邮件服务器。
*/
public String getServer()
{
return server;
}

/**
* 设置邮件服务器。
* @param server 邮件服务器。
*/
public void setServer(String server)
{
this.server = server;
}
}

(3) MailSender.java 文件。

import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import sun.misc.BASE64Encoder;

/**
* 使用 MailSender 来发送邮件。
* @author Dingli.
*/
public class MailSender
{
//发送或接收邮件的配置信息。
private MailConfig mailConfig = null;
//待发送的邮件对象。
private Mail mail = null;
//邮件会话对象。
private Session session = null;
//邮件发送者对象。
private Transport transport = null;
//MIME 消息对象。
private MimeMessage mimeMessage = null;
//MimeMultipart 对象。
private MimeMultipart mimeMultipart = null;

/**
* MailSender 类的默认构造方法。
*/
public MailSender()
{
this.mimeMultipart = new MimeMultipart();
}

/**
* MailSender 类的构造方法。
* @param mailConfig MailConfig 对象。
*/
public MailSender(MailConfig mailConfig)
{
this();
this.setMailConfig(mailConfig);
}

/**
* 设置发送或接收邮件的配置信息。
* @param mailConfig 发送或接收邮件的配置信息。
*/
public void setMailConfig(MailConfig mailConfig)
{
//设置邮件发送配置对象。
this.mailConfig = mailConfig;
//构建属性对象。
Properties properties = new Properties();
//设置发送邮件的协议。
properties.put("mail.transport.protocol", this.getMailConfig().getProtocol());
//设置是否需要身份验证。
properties.put("mail." + this.getMailConfig().getProtocol() + ".auth", "true");
//是否显示调试信息。
properties.put("mail.debug", String.valueOf(this.getMailConfig().isDebug()));
//启动一个邮件会话。
this.session = Session.getInstance(properties);
}

/**
* 获取发送或接收邮件的配置信息。
* @return 发送或接收邮件的配置信息。
*/
public MailConfig getMailConfig()
{
return mailConfig;
}

/**
* 设置邮件对象。
* @param mail 邮件对象。
* @throws Exception Exception 异常。
*/
public void setMail(Mail mail) throws Exception
{
if(this.mailConfig != null)
{
//保存邮件对象。
this.mail = mail;
//构建 MIME 消息对象。
this.mimeMessage = new MimeMessage(this.session);
//设置发件人。
this.mimeMessage.setFrom(new InternetAddress(this.getMail().getFrom()));
//设置邮件主题。
this.mimeMessage.setSubject(this.getMail().getSubject());
//设置邮件发送时间。
this.mimeMessage.setSentDate(this.getMail().getSendDate());
//设置收件人。
this.setMailRecipients(this.mimeMessage, Message.RecipientType.TO, this.getMail().getSendTo());
//设置抄送人。
this.setMailRecipients(this.mimeMessage, Message.RecipientType.CC, this.getMail().getCarbonCopy());
//设置暗送人。
this.setMailRecipients(this.mimeMessage, Message.RecipientType.BCC, this.getMail().getBlindCarbonCopy());
//判断邮件是否有附件。
if(this.getMail().getAttachment().isEmpty())
{
//设置邮件文本内容。
this.mimeMessage.setText(this.getMail().getContent());
}
else
{
//设置邮件内容。
this.setMailBody(this.getMail());
//设置Multipart对象。
this.mimeMessage.setContent(this.mimeMultipart);
}
}
else
{
throw new Exception("You must set mail config first");
}
}

/**
* 获取邮件对象。
* @return 邮件对象。
*/
public Mail getMail()
{
return mail;
}

/**
* 发送邮件。
* @param mail 邮件对象。
* @throws Exception Exception 异常。
*/
public void send(Mail mail) throws Exception
{
this.setMail(mail);
this.connect();
this.send();
}

/**
* 连接到配置信息设置的邮件服务器。
* @throws Exception Exception 异常。
*/
public void connect() throws Exception
{
if(this.getMail() != null)
{
//构建发送者。
this.transport = this.session.getTransport();
//连接到邮件服务器。
this.transport.connect(this.getMailConfig().getServer(), this.getMailConfig().getPort(), this.getMailConfig().getUser(), this.getMailConfig().getPassword());
}
else
{
throw new Exception("No such mail to set");
}
}

/**
* 关闭与邮件服务器的连接。
* @throws Exception Exception 异常。
*/
public void close() throws Exception
{
//关闭邮件发送者对象。
if(this.transport != null && this.transport.isConnected())
{
this.transport.close();
}
//置空对象。
this.mailConfig = null;
this.mail = null;
this.session = null;
this.transport = null;
this.mimeMultipart = null;
this.mimeMessage = null;
}

/**
* 发送邮件。
* @throws Exception Exception 异常。
*/
public void send() throws Exception
{
if(this.transport != null && this.transport.isConnected())
{
//发送邮件给收件人。
if(this.mimeMessage.getRecipients(Message.RecipientType.TO) != null)
{
this.transport.sendMessage(this.mimeMessage, this.mimeMessage.getRecipients(Message.RecipientType.TO));
}
//发送邮件给抄送人。
if(this.mimeMessage.getRecipients(Message.RecipientType.CC) != null)
{
this.transport.sendMessage(this.mimeMessage, this.mimeMessage.getRecipients(Message.RecipientType.CC));
}
//发送邮件给暗送人。
if(this.mimeMessage.getRecipients(Message.RecipientType.BCC) != null)
{
this.transport.sendMessage(this.mimeMessage, this.mimeMessage.getRecipients(Message.RecipientType.BCC));
}
}
else
{
throw new Exception("No such connection");
}
}

/**
* 设置收信人。
* @param mimeMessage MIME 消息类型。
* @param recipientType 收信人类型。
* @param recipients 收信人列表。
* @throws Exception Exception 异常。
*/
private void setMailRecipients(MimeMessage mimeMessage, RecipientType recipientType, List recipients) throws Exception
{
//构建收信人地址数组。
InternetAddress[] internetAddresses = new InternetAddress[recipients.size()];
//遍历所有收信人。
for(int i = 0; i < recipients.size(); i++)
{
//构建收信人地址对象。
internetAddresses[i] = new InternetAddress(recipients.get(i).toString());
}
//设置收信人。
mimeMessage.setRecipients(recipientType, internetAddresses);
}

/**
* 设置邮件体。包括邮件内容与附件。
* @param mail Mail 对象。
* @throws Exception Exception 异常。
*/
private void setMailBody(Mail mail) throws Exception
{
//移除 MimeMultipart 对象中的 MimeBodyPart 对象。
if(this.mimeMultipart != null)
{
//清空 MimeMultipart 对象。
for(int i = 0; i < this.mimeMultipart.getCount(); i++)
{
this.mimeMultipart.removeBodyPart(i);
}
}
//base64编码器。
BASE64Encoder base64Encoder = new BASE64Encoder();
//构建邮件文本内容对象。
MimeBodyPart textBodyPart = new MimeBodyPart();
//设置邮件文本内容。
textBodyPart.setText(mail.getContent());
//添加邮件文本内容。
this.mimeMultipart.addBodyPart(textBodyPart);
//遍历所有附件本地路径。
for(int i = 0; i < mail.getAttachment().size(); i++)
{
//邮件附件本地路径。
String attachmentPath = mail.getAttachment().get(i).toString();
//构建邮件附件对象。
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
//用文件数据源对象构建一个数据句柄对象并设置到邮件附件对象。
attachmentBodyPart.setDataHandler(new DataHandler(new FileDataSource(attachmentPath)));
//设置邮件附件对象的名字。
attachmentBodyPart.setFileName("=?GBK?B?" + base64Encoder.encode(attachmentPath.substring(attachmentPath.replace('\\', '/').lastIndexOf('/') + 1).getBytes()) + "?=");
//添加邮件附件。
this.mimeMultipart.addBodyPart(attachmentBodyPart);
}
}
}

用一个 main() 方法来简单表明如何使用。

public class MainClass
{
public static void main(String[] args)
{
//邮件发送者。
MailSender mailSender = new MailSender();
try
{
//SMTP 配置。
MailConfig mailConfig = new MailConfig();
//设置登录的邮件服务器。
mailConfig.setServer("smtp.126.com");
//设置登录用户名。
mailConfig.setUser("dingli717");
//设置登录密码。
mailConfig.setPassword("******");
//一封电子邮件.
Mail mail = new Mail();
//发件人。
mail.setFrom("dingli717@126.com");
//收件人,可以添加多个。
mail.getSendTo().add("dingli717@126.com");
//邮件主题。
mail.setSubject("Java 你好");
//邮件内容。
mail.setContent("邮件发送测试");
//本地附件路径,可以添加多个附件。
mail.setAttachment("E:/testExcel.xls");
//设置邮件配置。
mailSender.setMailConfig(mailConfig);
//设置要发送的邮件。
mailSender.setMail(mail);
//连接邮件服务器。
mailSender.connect();
//发送邮件。
mailSender.send();
//邮件成功发送。
System.out.println("邮件发送成功!");
}
catch(Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
mailSender.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}

Mail 类表示一封电子邮件,MailConfig 类表示发送或接收电子邮件的配置信息,而 MailSender 类用来处理邮件的具体发送。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值