简单的代码实现邮件发送的功能
发送邮件需要一个实体类
package com.fh.util.mail;
public class EmailParaForm {
//编号
private String id;
//发件人
private String tfrom;
//收件人,以分号分隔
private String tto;
//主题
private String ttitle;
//内容
private String tcontent;
//发送邮件服务器
private String stmpHost;
//接受邮件服务器
private String popHost;
//协议
private String protocol;
//是否需要认证
private String needAuth;
//验证类名
//private String authClassNm;
private String isDebug;
//抄送,以分号分隔
private String tcc;
//暗送,以分号分隔
private String tbcc;
//多附件以分号分隔
private String fileAttachments;
//用户名
private String userName;
//密码
private String password;
//代理服务器IP
private String agentIp;
//代理服务器端口号
private String agentPort;
//weblogin配置JavaMail:则需指定JNDI名检索
private String jndiNm;
//接收协议
private String pprotocol;
//发送邮件服务器端口
private String tport;
//接收邮件服务器端口
private String pport;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTfrom() {
return tfrom;
}
public void setTfrom(String tfrom) {
this.tfrom = tfrom;
}
public String getTto() {
return tto;
}
public void setTto(String tto) {
this.tto = tto;
}
public String getTtitle() {
return ttitle;
}
public void setTtitle(String ttitle) {
this.ttitle = ttitle;
}
public String getTcontent() {
return tcontent;
}
public void setTcontent(String tcontent) {
this.tcontent = tcontent;
}
public String getStmpHost() {
return stmpHost;
}
public void setStmpHost(String stmpHost) {
this.stmpHost = stmpHost;
}
public String getPopHost() {
return popHost;
}
public void setPopHost(String popHost) {
this.popHost = popHost;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getNeedAuth() {
return needAuth;
}
public void setNeedAuth(String needAuth) {
this.needAuth = needAuth;
}
public String getIsDebug() {
return isDebug;
}
public void setIsDebug(String isDebug) {
this.isDebug = isDebug;
}
public String getTcc() {
return tcc;
}
public void setTcc(String tcc) {
this.tcc = tcc;
}
public String getTbcc() {
return tbcc;
}
public void setTbcc(String tbcc) {
this.tbcc = tbcc;
}
public String getFileAttachments() {
return fileAttachments;
}
public void setFileAttachments(String fileAttachments) {
this.fileAttachments = fileAttachments;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAgentIp() {
return agentIp;
}
public void setAgentIp(String agentIp) {
this.agentIp = agentIp;
}
public String getAgentPort() {
return agentPort;
}
public void setAgentPort(String agentPort) {
this.agentPort = agentPort;
}
public String getJndiNm() {
return jndiNm;
}
public void setJndiNm(String jndiNm) {
this.jndiNm = jndiNm;
}
public String getPprotocol() {
return pprotocol;
}
public void setPprotocol(String pprotocol) {
this.pprotocol = pprotocol;
}
public String getTport() {
return tport;
}
public void setTport(String tport) {
this.tport = tport;
}
public String getPport() {
return pport;
}
public void setPport(String pport) {
this.pport = pport;
}
//set get方法
}
发送邮件具体实现
package com.fh.util.mail;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;
import org.apache.log4j.Logger;
/**
*
*
* @类编号:
* @类名称:EmailsUtils
* @内容摘要: 发送邮件
* @author:赵玉彬
* @创建日期:2017年5月21日 下午6:06:15
* @修改人:
* @修改日期:
* @修改描述:简单描述修改的内容
* @version 1.0.0
*
*/
public class EmailsUtils {
public static Logger logger = Logger.getLogger(EmailsUtils.class);
//Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
private static Multipart mp = new MimeMultipart();
private final static String CHAR_SET = "UTF-8";
/**
*
* @Description: 发送邮件
* @param EmailParaForm 发件人等发送邮件参数
*/
public static boolean SendEmails(EmailParaForm emailParaForm){
boolean isSucc = false;
if (emailParaForm == null){
return isSucc;
}
try{
//JavaMail需要Properties来创建一个session对象。它将寻找字符串"mail.smtp.host",属性值就是发送邮件的主机.
//Properties对象获取诸如邮件服务器、用户名、密码等信息,以及其他可在整个应用程序中 共享的信息。
Properties props=new Properties();//也可用Properties props = System.getProperties();
props.put("mail.smtp.host",emailParaForm.getStmpHost());//存储发送邮件服务器的信息
props.put("mail.smtp.port", "" + emailParaForm.getTport()); // 端口号
props.put("mail.transport.protocol",emailParaForm.getProtocol());
props.put("mail.smtp.auth",emailParaForm.getNeedAuth());//同时通过验证
if (null != emailParaForm.getAgentIp() && emailParaForm.getAgentIp().length() != 0 && !emailParaForm.getAgentIp().equals("0")) {
props.put("mail.agentIp", emailParaForm.getAgentIp());
}
if (null != emailParaForm.getAgentPort() && emailParaForm.getAgentPort().length() != 0 && !emailParaForm.getAgentPort().equals("0")) {
props.put("mail.agentPort", emailParaForm.getAgentPort());
}
Session s = Session.getInstance(props,null);//根据属性新建一个邮件会话,null参数是一种Authenticator(验证程序) 对象
String isDebug = emailParaForm.getIsDebug();
if (isDebug != null && isDebug.trim().equalsIgnoreCase("true")){
s.setDebug(true);//设置调试标志,要查看经过邮件服务器邮件命令,可以用该方法
}
Message message=new MimeMessage(s);//由邮件会话新建一个消息对象
//message.setContent("hello","test/plain");//设置消息的内容类型,如果发送的格式有HTML格式就必须设置,
//message.setText("Hello");//发送一般文本格式的消息
//设置邮件,一旦您创建了 Session 和 Message,并将内容填入消息后,就可以用Address确定信件地址了。
//如果想让一个名字出现在电子邮件地址后,也可以将其传递给构造器:
//Address from=new InternetAddress("xmqds@21cn.com","qdison");//发件人的邮件地址
Address from=new InternetAddress(emailParaForm.getTfrom());//发件人的邮件地址
message.setFrom(from);//设置发件人
Address to=new InternetAddress(emailParaForm.getTto());//收件人的邮件地址
message.setRecipient(Message.RecipientType.TO,to);//设置收件人,并设置其接收类型为TO,还有3种预定义类型如下:
message.setRecipient(Message.RecipientType.CC,from);
//Message.RecipientType.TO 收件人
//Message.RecipientType.CC 抄送
//Message.RecipientType.BCC 暗送
message.setSubject(emailParaForm.getTtitle());//设置主题
message.setSentDate(new Date());//设置发信时间
setBody(emailParaForm.getTcontent());
//String fileAttachment = "C:\\测试\\中国.txt";
//添加附件
String fileAttachments = emailParaForm.getFileAttachments();
if(null!=fileAttachments){
String[] fileAttArr = fileAttachments.split(";");
for (int i = 0; i < fileAttArr.length; i++){
String fileAtt = fileAttArr[i];
addFileAffix(fileAtt);
}
}
message.setContent(mp);
message.saveChanges();//存储邮件信息
// Transport 是用来发送信息的,
// 用于邮件的收发打操作。
Transport transport=s.getTransport(emailParaForm.getProtocol());
transport.connect(emailParaForm.getStmpHost(),emailParaForm.getUserName(),emailParaForm.getPassword());//以smtp方式登录邮箱
transport.sendMessage(message,message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址
transport.close();
isSucc = true;;
} catch(MessagingException e){
logger.error(e);
e.printStackTrace();
}
return isSucc;
}
/**
* 邮件添加附件
*
* @param filePath 包括路径名的完整本地文件名
* @return boolean
*/
public static boolean addFileAffix(String filePath) {
try {
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filePath);
bp.setDataHandler(new DataHandler(fileds));
String fileNm = fileds.getName();
bp.setFileName(MimeUtility.encodeText(fileNm));
mp.addBodyPart(bp);
return true;
}
catch (Exception e) {
logger.error(e);
System.err.println("Affix" + filePath + "accour error" + e);
return false;
}
}
/**
* 设置邮件内容
*
* @param body 邮件内容
* @return boolean
*/
public static boolean setBody(String body) {
try {
BodyPart bp = new MimeBodyPart();
bp.setContent("" + body, "text/html;charset=" + CHAR_SET);
mp.addBodyPart(bp);
return true;
} catch (Exception e) {
logger.error(e);
System.err.println("set mail body is error" + e);
return false;
}
}
/**
* 发送邮件
* @param receiveUser 接收人
* @param title 标题
* @param content 内容
* 返回true则发送成功,false发送失败
* @return
*/
public static boolean send(String receiveUser,String title,String content){
boolean isSucc = false;
EmailParaForm spForm = new EmailParaForm();
spForm.setId("FFFFFF");
spForm.setTfrom("zhaoyubin2015@163.com"); // 发出者邮箱
spForm.setStmpHost("smtp.163.com"); // 邮箱类型
spForm.setNeedAuth("true");//是否需要认证
spForm.setIsDebug("false"); //调试
spForm.setProtocol("smtp"); //协议
spForm.setUserName("zhaoyubin2015@163.com");//用户名
spForm.setPassword("****");//密码
spForm.setTport("25");//端口。默认发出
spForm.setTto(receiveUser);
spForm.setTcontent(content);
spForm.setTtitle(title);
String formPass = spForm.getPassword();
if (formPass != null ){
isSucc=SendEmails(spForm);
}
return isSucc;
}
public static void main(String[] args){
EmailsUtils e = new EmailsUtils();
e.send("2148889217@qq.com", "工作日报", "这里是匠网制版有限公司的工作日报。");
}
}
注:发送邮件的账号需打开授权。