Java封装好的mail包发送电子邮件的类
程序员文章站
2024-03-08 21:41:10
下面代码是利用java mail包封装了一个发送邮件的类
import java.io.file;
import java.util.arraylist;
i...
下面代码是利用java mail包封装了一个发送邮件的类
import java.io.file; import java.util.arraylist; import java.util.date; import java.util.list; import java.util.properties; import javax.activation.datahandler; import javax.activation.filedatasource; import javax.mail.message; import javax.mail.messagingexception; import javax.mail.multipart; 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; public class sendmail { private static final string mail_address_regex = "^[\\w\\.=-]+@[\\w\\.-]+\\.[\\w]{2,3}$"; private string mailserver; private string sender; private string[] receiver; public sendmail(){ } public void setmailbasicinfo(string mailserver,string sender,string receiver){ this.mailserver = mailserver; this.sender = sender; this.receiver =receiver.split(","); } public void setmailbasicinfo(string mailserver,string sender,string[] users){ this.mailserver = mailserver; this.sender = sender; this.receiver = users; } public void setmailbasicinfo(string mailserver,string sender,list<string> users){ this.mailserver = mailserver; this.sender = sender; this.receiver = new string[users.size()]; users.toarray(this.receiver); } public boolean send(string subject, string content, list<string> filenames) { subject = subject==null?"":subject; content = content==null?"":content; properties props = new properties(); props.put("mail.smtp.host", mailserver); session session = session.getinstance(props, null); try { internetaddress[] receiver = getreceiverlist(); if (receiver.length == 0) { system.out.println("receiver is null"); return false; } mimemessage msg = new mimemessage(session); msg.setfrom(new internetaddress(sender)); msg.setrecipients(message.recipienttype.to, receiver); msg.setsubject(subject); msg.setsentdate(new date()); multipart container = new mimemultipart(); mimebodypart textbodypart = new mimebodypart(); textbodypart.setcontent(content.tostring(), "text/html;charset=gbk"); container.addbodypart(textbodypart); doattachfile(container,filenames); msg.setcontent(container); system.out.println("begin send mail"); transport.send(msg); system.out.println("send mail success"); } catch (messagingexception e) { system.out.println("send mail fail"); system.out.println(e); return false; } catch(exception e){ return false; } return true; } public boolean send(string subject, string content){ return send(subject,content,null); } public boolean send(string subject){ return send(subject,null); } private void doattachfile(multipart container, list<string> filenames) throws messagingexception{ if(filenames==null || filenames.size()==0) return; for(string filename:filenames){ file f = new file(filename); if(!f.isfile()) continue; system.out.println("the attach file is:"+filename); mimebodypart filebodypart = new mimebodypart(); filedatasource fds = new filedatasource(f);// 要发送的附件地址 filebodypart.setdatahandler(new datahandler(fds)); filebodypart.setfilename(fds.getname());// 设置附件的名称 container.addbodypart(filebodypart); } } private internetaddress[] getreceiverlist() throws addressexception { arraylist<internetaddress> tolist = new arraylist<internetaddress>(); for (int i = 0; i < receiver.length; ++i) { if (receiver[i].matches(mail_address_regex)) { tolist.add(new internetaddress(receiver[i])); } } return (internetaddress[]) tolist.toarray(new internetaddress[tolist.size()]); } }
使用举例
string host = "168.xx.xx.xx"; //邮件服务器的地址 string subject = "发送邮件的主题"; string sender = "test@gmail.com"; list<string> receivers = new arraylist<string>(); receivers.add("user1@263.com"); receivers.add("user2@263.com"); string content = "邮件主题"; sendmail sendmail = new sendmail(); sendmail.setmailbasicinfo(host, sender, receivers); sendmail.send(subject, content, null); //没有附件
正文也可以是html内容,如
string content = "<html>详细信息:<a href='xxxx'>请点击查看!</a></html>";
我们再来看一个封装好的类
package com.message.base.email; import com.message.base.spring.applicationhelper; import com.message.base.utils.stringutils; import com.message.base.utils.validateutils; import org.slf4j.logger; import org.slf4j.loggerfactory; import javax.mail.*; import javax.mail.internet.internetaddress; import javax.mail.internet.mimemessage; import java.util.collections; import java.util.date; import java.util.list; import java.util.properties; /** * 发送邮件服务器. * * @author sunhao(sunhao.java@gmail.com) * @version v1.0, 13-3-25 上午6:19 */ public class emailserver { private static final logger logger = loggerfactory.getlogger(emailserver.class); //spring中配置 /**邮箱服务器配置**/ private list<emailconfig> config; /**是否开启debug调试模式**/ private boolean isdebug = false; /**是否启用身份验证**/ private boolean isauth = true; /**验证类型**/ private string authtype = "auth"; /** * 私有化默认构造器,使外部不可实例化 */ private emailserver(){} /** * 单例,保证上下文中只有一个emailserver * * @return emailserver */ public static emailserver getinstance(){ return applicationhelper.getinstance().getbean(emailserver.class); } /** * 发送普通邮件(单个接收人) * * @param username 发件人用户名 * @param password 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param receiver 单个接收人 * @return */ public boolean sendtextmail(string username, string password, string title, string content, string receiver){ return this.sendtextmail(username, password, title, content, collections.singletonlist(receiver)); } /** * 发送普通邮件(多个接收人) * * @param username 发件人用户名 * @param password 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param receivers 多个接收人 * @return */ public boolean sendtextmail(string username, string password, string title, string content, list<string> receivers){ authentication auth = null; if(this.isauth()){ //如果需要身份认证,则创建一个密码验证器 auth = new authentication(username, password); } properties props = new properties(); props.setproperty("mail.smtp.auth", this.isauth() ? "true" : "false"); props.setproperty("mail.transport.protocol", "auth"); emailconfig config = this.getemailconfig(username); props.setproperty("mail.smtp.host", config.getsmtp()); props.setproperty("mail.smtp.port", config.getport() + ""); // 根据邮件会话属性和密码验证器构造一个发送邮件的session session session = session.getdefaultinstance(props, auth); session.setdebug(this.isdebug); message message = this.maketextmail(session, title, content, username, receivers, false); try { transport.send(message); return true; } catch (messagingexception e) { logger.error(e.getmessage(), e); return false; } } /** * 发送html邮件(单个接收人) * * @param username 发件人用户名 * @param password 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param receiver 单个接收人 * @return */ public boolean sendhtmlmail(string username, string password, string title, string content, string receiver){ return this.sendhtmlmail(username, password, title, content, collections.singletonlist(receiver)); } /** * 发送html邮件(多个接收人) * * @param username 发件人用户名 * @param password 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param receivers 多个接收人 * @return */ public boolean sendhtmlmail(string username, string password, string title, string content, list<string> receivers){ authentication auth = null; if(this.isauth()){ //如果需要身份认证,则创建一个密码验证器 auth = new authentication(username, password); } properties props = new properties(); props.setproperty("mail.smtp.auth", this.isauth() ? "true" : "false"); props.setproperty("mail.transport.protocol", "auth"); emailconfig config = this.getemailconfig(username); props.setproperty("mail.smtp.host", config.getsmtp()); props.setproperty("mail.smtp.port", config.getport() + ""); // 根据邮件会话属性和密码验证器构造一个发送邮件的session session session = session.getdefaultinstance(props, auth); session.setdebug(this.isdebug); message message = this.maketextmail(session, title, content, username, receivers, true); try { transport.send(message); return true; } catch (messagingexception e) { logger.error(e.getmessage(), e); return false; } } /** * 获取邮件服务器配置 * * @param email 邮箱地址 * @return */ private emailconfig getemailconfig(string email){ string mailservicedomainname = this.getmailservicedomainname(email); for(emailconfig config : this.config) { if(config.getname().equals(mailservicedomainname)){ return config; } } return null; } /** * 创建邮件message * * @param session 根据配置获得的session * @param title 邮件主题 * @param content 邮件的内容 * @param from 发件者 * @param receivers 收件者 * @param ishtmlmail 是否是html邮件 */ private message maketextmail(session session, string title, string content, string from, list<string> receivers, boolean ishtmlmail){ message message = new mimemessage(session); try { /**标题**/ logger.info("this mail's title is {}", title); message.setsubject(title); /**内容**/ logger.info("this mail's content is {}", content); if(ishtmlmail){ //是html邮件 message.setcontent(content, "text/html;charset=utf-8"); } else { //普通邮件 message.settext(content); } /**发件者地址**/ logger.info("this mail's sender is {}", from); address fromaddress = new internetaddress(from); message.setfrom(fromaddress); /**接收者地址**/ address[] tos = new internetaddress[receivers.size()]; for(int i = 0; i < receivers.size(); i++){ string receiver = receivers.get(i); if(validateutils.isemail(receiver)){ tos[i] = new internetaddress(receiver); } } /**发件时间**/ message.setsentdate(new date()); message.setrecipients(message.recipienttype.to, tos); } catch (messagingexception e) { logger.error(e.getmessage(), e); e.printstacktrace(); } return message; } /** * 获取邮箱域名 * * @param email 邮箱 * @return */ private string getmailservicedomainname(string email){ if(stringutils.isempty(email)){ return ""; } else { int firstindex = stringutils.indexof(email, "@"); int secondindex = stringutils.lastindexof(email, "."); return stringutils.substring(email, firstindex + 1, secondindex); } } public list<emailconfig> getconfig() { return config; } public void setconfig(list<emailconfig> config) { this.config = config; } public boolean isdebug() { return isdebug; } public void setdebug(boolean debug) { isdebug = debug; } public boolean isauth() { return isauth; } public void setauth(boolean auth) { isauth = auth; } public string getauthtype() { return authtype; } public void setauthtype(string authtype) { this.authtype = authtype; } }
调用方式如下
public boolean sendmail() throws exception { list<string> receivers = new arraylist<string>(); receivers.add("sunhao0550@163.com"); receivers.add("sunhao0550@sina.cn"); emailserver.getinstance().sendhtmlmail("message_admin@163.com", "这里是密码", "测试发送html邮件", "<span style='color: red;font-size: 20pt'>测试发送html邮件</span><a href='http://www.baidu.com' target='_blank'>链接到百度</a>", receivers); return emailserver.getinstance().sendtextmail("message_admin@163.com", "这里是密码", "测试发送文本邮件", "测试发送文本邮件测试发送文本邮件测试发送文本邮件", receivers); }
ps:正在考虑扩展,如果把这几个类封在jar包中,如何进行邮件服务器配置的扩展.
如有不好之处,欢迎拍砖.