Package Com.reagle.bean;
Import Java.util.Date; Import java.util.List; 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.Part; Import javax.mail.PasswordAuthentication; Import javax.mail.Session; Import Javax.mail.Transport; Import Javax.mail.URLName; 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 Org.apache.log4j.LogManager; Import Org.apache.log4j.Logger;
public class Mailbean { Private Logger log = Logmanager.getlogger (Mailbean.class); /** * Theme */ Private String subject; /** * Send email address */ Private String SendMail; /** * Send mailbox password */ Private String Sendmailpassword; /** * Recipient */ Private list<string> tos; /** * CC */ Private list<string> CCS; /** * Send content */ Private String content; /** * Content Encoding */ Private String character; /** * Send server address */ Private String mailhost; /** * Annex */ Private list<string> accessories; /** * Whether to send a check */ Private String ischecksend; /** * * @param subject Theme * @param sendMail Sender * @param sendmailpassword Password * @param TOS Recipients * @param content * @param character Content character set * @param mailhost SMTP Host * @param ischecksend whether to verify */ Public Mailbean (string subject, String SendMail, String Sendmailpassword, List<string> tos, string content, string character, String mailhost, String ischecksend) { This.subject = subject; This.sendmail = SendMail; This.sendmailpassword = Sendmailpassword; This.tos = TOS; this.content = content; This.character = character; This.mailhost = Mailhost; This.ischecksend = Ischecksend; } /** * * @param subject Theme * @param sendMail Sender * @param sendmailpassword Password * @param TOS Recipients * @param content * @param character Content character set * @param mailhost SMTP Host * @param ischecksend whether to verify * @param Accessories Accessories */ Public Mailbean (string subject, String SendMail, String Sendmailpassword, List<string> tos, string content, string character, String mailhost, List<string> accessories, string ischecksend) { This.subject = subject; This.sendmail = SendMail; This.sendmailpassword = Sendmailpassword; This.tos = TOS; this.content = content; This.character = character; This.mailhost = Mailhost; This.accessories = accessories; This.ischecksend = Ischecksend; } /** * * @param subject Theme * @param sendMail Sender * @param sendmailpassword Password * @param TOS Recipients * @param content * @param character Content character set * @param mailhost SMTP Host * @param ischecksend whether to verify * @param Accessories Accessories * @param cc CC */ Public Mailbean (string subject, String SendMail, String Sendmailpassword, List<string> Takemail, string content, string character, String mailhost, List<string> accessories, String ischecksend, list<string> cc) { This.subject = subject; This.sendmail = SendMail; This.sendmailpassword = Sendmailpassword; This.tos = Takemail; this.content = content; This.character = character; This.mailhost = Mailhost; This.accessories = accessories; This.ischecksend = Ischecksend; This.ccs = CC; } Public String Getsubject () { return subject; } public void Setsubject (String subject) { This.subject = subject; } Public String Getsendmail () { return sendMail; } public void Setsendmail (String sendMail) { This.sendmail = SendMail; } Public String Getsendmailpassword () { return Sendmailpassword; } public void Setsendmailpassword (String sendmailpassword) { This.sendmailpassword = Sendmailpassword; }
Public String getcontent () { return content; } public void SetContent (String content) { this.content = content; } Public String Getcharacter () { return character; } public void Setcharacter (String character) { This.character = character; } Public String Getmailhost () { return mailhost; } public void Setmailhost (String mailhost) { This.mailhost = Mailhost; } Public list<string> getaccessories () { return accessories; } public void Setaccessories (List<string> accessories) { This.accessories = accessories; } Public String Getchecksend () { return ischecksend; } public void Setchecksend (String ischecksend) { This.ischecksend = Ischecksend; } Public list<string> Gettos () { return TOS; } public void Settos (list<string> tos) { This.tos = TOS; } Public list<string> Getccs () { return to CCS; } public void Setccs (list<string> CCS) { This.ccs = CCS; } Public String Getischecksend () { return ischecksend; } public void Setischecksend (String ischecksend) { This.ischecksend = Ischecksend; } Get all recipients Private address[] Getalltake () throws ArrayIndexOutOfBoundsException, addressexception{ Return valueofaddress (TOS); } Private address[] Valueofaddress (list<string> List) throws ArrayIndexOutOfBoundsException, addressexception{ Address[] takes = new address[0]; if (null = = List | | list.size () = 0) throw new ArrayIndexOutOfBoundsException ("list is null"); takes = new address[list.size ()]; for (int i = 0; i < list.size (); + + i) { Takes[i] = Internetaddress.parse (List.get (i)) [0]; } return takes; } Private address[] Getallothertake () throws ArrayIndexOutOfBoundsException, Addressexception { if (null = CCS | | ccs.size () = 0) return new Address[0]; Else Return valueofaddress (Getccs ()); } Add all Attachments private void Addbodypartbymimemultipart (Mimemultipart mm, List<string> filepaths) throws Messagingexception, ArrayIndexOutOfBoundsException, NullPointerException {
if (null = = Filepaths | | filepaths.size () = 0) Return if (null = mm) throw new NullPointerException ("Mimemultipart is null"); for (int i = 0; i < filepaths.size (); i++) { MimeBodyPart bp = new MimeBodyPart (); Filedatasource fileds = new Filedatasource (Filepaths.get (i)); DataHandler dh = new DataHandler (fileds); Bp.setdisposition (part.attachment); Bp.setfilename (Fileds.getname ()); Bp.setdatahandler (DH); Mm.addbodypart (BP); } }
public Boolean send () throws Exception { Boolean issend = false;
Set up SMTP send server Properties props = System.getproperties ();
To set the host for SMTP Props.put ("Mail.smtp.host", mailhost);
Need to be validated Props.put ("Mail.smtp.auth", ischecksend); Authenticator auth = Authenticator
Get mail Session Object Session session = Session.getdefaultinstance (props,null); URLName URL = new URLName (This.sendmail); Passwordauthentication pw = new Passwordauthentication (This.sendmail, This.sendmailpassword); Session.setpasswordauthentication (URL, pw);
Mail Object MimeMessage mimemsg = new MimeMessage (session); Mimemultipart multipart = new Mimemultipart ();
Send mail address Mimemsg.setfrom (New InternetAddress (SendMail));
Recipient Mimemsg.setrecipients (Message.RecipientType.TO, Getalltake ());
Mimemsg.setsentdate (New Date ()); CC person Mimemsg.setrecipients (Message.RecipientType.CC, Getallothertake ());
Subject and character encoding Mimemsg.setsubject (Getsubject (), Getcharacter ());
Set Message size BodyPart bp = new MimeBodyPart (); Bp.setcontent ("<meta http-equiv=content-type content=text/html; Charset= "+getcharacter () +" > " + Content, "text/html;charset=" +getcharacter ());
Bp.settext (content);
Log.info (Bp.getcontent (). toString ()); Multipart.addbodypart (BP);
Add attachment Addbodypartbymimemultipart (multipart, getaccessories ());
Issend = Process (Session, mimemsg, multipart, props);
return issend; }
Private Boolean process (session session, MimeMessage Mimemsg, Mimemultipart multipart, Properties props) throws messaging Exception { Boolean issuccessfully = false; Mimemsg.setcontent (multipart); Mimemsg.savechanges (); Session mailsession = session.getinstance (props, null); Transport transport = Mailsession.gettransport ("SMTP"); Transport.connect ((String) props.get ("Mail.smtp.host"), Getsendmail (), Getsendmailpassword ()); Transport.sendmessage (Mimemsg, mimemsg.getallrecipients ()); Log.info ("Mail successfully sended!"); Transport.close (); Issuccessfully = true; return issuccessfully; }
} Mail Tool class /** * */ Package com.reagle.util.others; Import java.io.IOException; Import java.util.Properties; Import Org.apache.commons.lang.StringUtils; Import Org.apache.log4j.LogManager; Import Org.apache.log4j.Logger; /** * @Program Name:reaglews.com.reagle.util.others.MailUtil.java * @Written BY:KZW * @version: v1.00 * @Creation DATE:2012-7-17 10:40:40 * @Description: * Mail Operation Tool Class * @ModificationHistory * Who when What * ------- ------------- ----------------- * KZW 2012-7-17 Morning 10:40:40 Create * **/ public class Mailutil { private static Logger log = Logmanager.getlogger (Mailutil.class);
private static final String Configpath = "Mail.properties"; Private static final String SMTP = "SMTP"; private static final String Emailregex = "Emailregex"; private static Properties Mailconfig;
static { Reloadpro (); } /** * Get mailbox corresponding SMTP server * by mail to determine the required SMTP host, where the default is the use of QQ SMTP server * @Eclosing_Method: GETMAIL2SMTP * @author BY:KZW * @creation DATE:2012-7-17 11:02:33 * @param mail * @return * */ public static string Getmail2smtp (String mail) { Return (String) getconfigvalue (SMTP); } public static string Getconfigvalue (String key) { if (null = = Mailconfig) Reloadpro (); Return (String) mailconfig.get (key); } /** * Reload configuration file * @Eclosing_Method: Reloadpro * @author BY:KZW * @creation DATE:2012-7-17 11:57:19 * */ public static void Reloadpro () { Mailconfig = new Properties (); try { Mailconfig.load (MailUtil.class.getClassLoader (). getResourceAsStream (Configpath)); catch (IOException e) { Log.error ("Load message configuration Error!") E= "+ e.getmessage ()); } } /** * Email address is correct * @Eclosing_Method: Isemail * @author BY:KZW * @creation DATE:2012-7-17 12:17:28 * @param Email * @return * */ public static Boolean isemail (String email) { if (Stringutils.isnotblank (email)) Return Email.matches (Getconfigvalue (Emailregex)); return false; } } Mail configuration file Mail.properties # # Mail Send configuration file # # KZW Create 2012-07-17 # # #
#邮件内容字符集 Character=utf-8 #SMTP Smtp=smtp.exmail.qq.com #默认发送者 Defaultsend=xxxxx #密码 Password=xxxxxx #是否需要发送验证 Checksend=true #邮箱校验正则 emailregex=^ ([a-z0-9a-z]+[_|\.]?) +[a-z0-9a-z]@ ([a-z0-9a-z]+ (-[a-z0-9a-z]+).) +[a-za-z]{2,}$ Mail interface Package com.reagle.server;
Import java.util.List;
/** * @Program Name:reaglews.com.reagle.server.IMailService.java * @Written BY:KZW * @version: v1.00 * @Creation DATE:2012-7-17 09:29:30 * @Description: * Mail Interface * @ModificationHistory * Who when What * ------- ------------- ----------------- * KZW 2012-7-17 Morning 09:29:30 Create * **/ Public interface Imailservice { /** * Character Set configuration key, here is a bit strange, after the optimization//todo .... */ Public final String characterconfig = "character"; Public final String smtpconfig = "SMTP"; Public final String checksend = "Checksend"; Public final String default_send = "Defaultsend"; Public final String default_send_pwd = "password"; /** * Send mail * @Eclosing_Method: SendMail * @author BY:KZW * @creation DATE:2012-7-17 10:08:50 * @param sendmailaddr Sender's mailbox * @param sendmailpwd Sender Password * @param cc CC person * @param to Recipient * @param subject Mail subject * @param contents of content messages * @param Accessories Accessories * @param mailtype Message type * @param operman operator * @param Memo Notes * */ void SendMail (String sendmailaddr, String sendmailpwd, List<string> cc, List<string> to, string subject, string content, list<string> accessories, String Mailtype, String Operman, String memo);
} Mail interface Implementation Class /** * */ Package Com.reagle.server.impl; Import Java.math.BigDecimal; Import Java.text.SimpleDateFormat; Import java.util.ArrayList; Import Java.util.Arrays; Import Java.util.Date; Import java.util.List; Import Java.util.concurrent.BlockingQueue; Import Java.util.concurrent.LinkedBlockingQueue; Import Java.util.concurrent.ThreadPoolExecutor; Import Java.util.concurrent.TimeUnit;
Import Org.apache.commons.lang.StringUtils; Import Org.apache.log4j.LogManager; Import Org.apache.log4j.Logger; Import Com.reagle.bean.MailBean; Import Com.reagle.common.db.DbUtilsTemplate; Import Com.reagle.server.IMailService; Import Com.reagle.util.others.MailUtil;
/** * @Program Name:reaglews.com.reagle.server.impl.MailServiceImpl.java * @Written BY:KZW * @version: v1.00 * @Creation DATE:2012-7-17 10:10:32 * @Description: Mail Interface implementation * @ModificationHistory who What------------------------------------- * KZW 2012-7-17 Morning 10:10:32 Create * **/ public class Mailserviceimpl implements Imailservice { private static Logger log = Logmanager.getlogger (Mailserviceimpl.class);
/* Pool Config */ private static final int corepoolsize = 10; private static final int maximumpoolsize = 20; Maximum number of connections
private static Threadpoolexecutor pool; private static blockingqueue<runnable> queue = new linkedblockingqueue<runnable> ();
static { /** * Using a thread pool in the JDK, threads executing a borderless policy */ Pool = new Threadpoolexecutor (Corepoolsize, Maximumpoolsize, 2, timeunit.minutes, queue); } @Override public void SendMail (string sendmailaddr, String sendmailpwd, list<string> CCS, list<string> tos, String subject, String content, List<string> accessories, String mailtype, String Operman, String memo) { Mailthread mail = new Mailthread (); Mail.init (SENDMAILADDR, SENDMAILPWD, CCS, TOS, subject, content, accessories, Mailtype, Operman, Memo); Pool.execute (mail); } /** * * @Program Name:reaglews.com.reagle.server.impl.MailServiceImpl.java * @Written BY:KZW * @version: v1.00 * @Creation date:2012-7-18 04:14:23 * @Description: * Send mail thread * @ModificationHistory * Who when What * ------- ------------- ----------------- * KZW 2012-7-18 PM 04:14:23 Create * * */ Class Mailthread implements Runnable { Private Logger Logger = Logmanager.getlogger (Mailthread.class);
Private list<string> CCS; Private list<string> tos; Private list<string> accessories;
Private String sendmailaddr; Private String sendmailpwd; Private String subject; Private String content; Private String Mailtype; Private String Operman; Private String Memo;
Private SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); /** * Initialization of thread data * @Eclosing_Method: Init * @author BY:KZW * @creation DATE:2012-7-17 05:25:48 * @param sendmailaddr * @param sendmailpwd * @param CCS CC number * @param TOS Recipients * @param subject Theme * @param content * @param Accessories Accessories * */ public void init (string sendmailaddr, String sendmailpwd, list<string> CCS, list<string> tos, String subject, String content, List<string> accessories, String mailtype, String Operman, String memo) { THIS.SENDMAILADDR = sendmailaddr; This.sendmailpwd = sendmailpwd; This.ccs = CCS; This.tos = TOS; This.subject = subject; this.content = content; This.accessories = accessories; This.mailtype = Mailtype; This.operman = Operman; This.memo = Memo; } @Override public void Run () { Logger.info ("Send mail Start" + sdf.format (new Date ()); int id = 0; String flag = "0"; Ready to send String msg = ""; Send a message Boolean res = false;//Send results try { id = getseqno (); Ccs.addall (Queryccsbymailtype (Mailtype)); Add a CC-Required email address Use the default mailbox if (Stringutils.isblank (sendmailaddr)) { SENDMAILADDR = Mailutil.getconfigvalue (default_send); Sendmailpwd = Mailutil.getconfigvalue (DEFAULT_SEND_PWD); }
Insert Outgoing mail log Savelog (SENDMAILADDR, CCS, TOS, subject, content, accessories, Mailtype, Operman, Memo, IDS);
Verify the data and remove the wrong email address if (!validate (SENDMAILADDR, SENDMAILPWD, CCS, TOS, subject, content, accessories)) { Logger.error ("Verify mail data fails"); Return } Get Mail Object Mailbean mail = getmailinstance (sendmailaddr, SENDMAILPWD, CCS, TOS, subject, content, accessories);
Send mail res = Mail.send (); Flag = res? "1": "2"; if (!res) msg = "Unknown error, send failed"; Update Send record Modifylog (MSG, flag, ID);
catch (Exception e) { E.printstacktrace (); Logger.error (E.getmessage (), E); Modifylog (E.getmessage (), "2", id); } Logger.info ("Send mail End" + Sdf.format (new Date ()); }
/** * Get mail Object entity * @Eclosing_Method: getinstance * @author BY:KZW * @creation DATE:2012-7-17 03:16:02 * @param sendmailaddr Sender * @param sendmailpwd Sender Password * @param CCS CC * @param TOS Recipients * @param subject Theme * @param content * @param Accessories Accessories * @return * */ Private Mailbean getmailinstance (string sendmailaddr, String sendmailpwd, list<string> CCS, list<string> tos, String subject, String content, list<string> accessories) { Get SMTP Address String mailhost = MAILUTIL.GETMAIL2SMTP (SENDMAILADDR);
Create a message Mailbean mail = new Mailbean (subject, SENDMAILADDR, Sendmailpwd, TOS,//Recipient Content Mailutil.getconfigvalue (Characterconfig), Mailhost, Accessories,//Accessories Mailutil.getconfigvalue (Checksend), CCS//CC );
return mail; }
Private Boolean Validate (String sendmailaddr, String sendmailpwd, List<string> transmitmails, list<string> takemail, String subject, String content, list<string> multiparts) { Boolean res = true; if (! Mailutil.isemail (sendmailaddr)) res = false; Clear Error number CANCELERRORMAILADDR (transmitmails); CANCELERRORMAILADDR (Takemail);
return res; }
private void Cancelerrormailaddr (list<string> List) { if (null = = List | | list.isempty ()) return; List<string> back = new arraylist<string> (list); for (String Email:back) { if (! Mailutil.isemail (email)) { List.remove (email); Log.info ("Remove error message:" + email); } } }
private int getseqno () { String seqsql = "Select Seq_mail.nextval from Dual"; BigDecimal B = (BigDecimal) new Dbutilstemplate (). FindBy (Seqsql, 1); return B.intvalue (); }
Private Boolean Savelog (String sendMail, list<string> CCS, list<string> tos, string subject, String content, List<string> accessories, String mailtype, String Operman, String memo, int id) {
StringBuffer sql = new StringBuffer (); Sql.append ("INSERT into Mail_send_detail"); Sql.append ("(ID, SendMail, Senddate, TOS, CCS, subject, Context, status,"); Sql.append ("Mailtype, Accessories, Operman, Operdate,opermemo") VALUES (?,?, sysdate,?,?,?,?, ' 0 ',?,?,?, sysdate,? )");
String[] params = { String.valueof (ID), SendMail, Arrays.tostring (Ccs.toarray ()). replace ("[", ""). Replace ("]", ""), Arrays.tostring (Tos.toarray ()). replace ("[", ""). Replace ("]", ""), Subject Content Mailtype, Arrays.tostring (Accessories.toarray ()). replace ("[", ""). Replace ("]", ""), Operman, Memo };
return (1 = = new Dbutilstemplate (). Update (Sql.tostring (), params)); }
Private Boolean Modifylog (String memo, string flag, int id) { String sql = "Update mail_send_detail set status=?, Memo =?" WHERE id =? "; return (1 = = new Dbutilstemplate (). Update (SQL, New String[]{flag, Memo, string.valueof (ID)}); } To query the message type, CC Private list<string> Queryccsbymailtype (String mailtype) { list<string> list = new arraylist<string> (); String sql = "Select CCS from Dm_mail_type where dm01=?"; String emails = (string) new Dbutilstemplate (). FindBy (SQL, 1, mailtype); if (Stringutils.isnotblank (emails)) { List = Arrays.aslist (Emails.split (";")); } return list; } } } Unit Test /** * */ Package com.reagle.IMailService; Import Java.text.SimpleDateFormat; Import java.util.ArrayList; Import Java.util.Date; Import java.util.List; Import Org.junit.Before; Import Org.junit.Test; Import Com.reagle.server.IMailService; Import Com.reagle.server.impl.MailServiceImpl; /** * @Program Name:reaglews.com.reagle.IMailService.TestMailService.java * @Written BY:KZW * @version: v1.00 * @Creation date:2012-7-18 09:07:25 * @Description: * * @ModificationHistory * Who when What * ------- ------------- ----------------- * KZW 2012-7-18 Morning 09:07:25 Create * **/ public class Testmailservice { Imailservice Service; List<string> transmitmails; List<string> Takemail; List<string> Multiparts; @Before public void init () { Service = new Mailserviceimpl (); Transmitmails = new arraylist<string> (); Takemail = new arraylist<string> (); Multiparts = new arraylist<string> (); Takemail.add ("100086@qq.com"); }
@Test public void Testthreadpool () throws interruptedexception{ Strategy 1 Submit 1000 requests at the same time int size = 1000; Long start = System.currenttimemillis (); for (int i = 0; i < size; i++) Service.sendmail (null, NULL, transmitmails, Takemail, "sub" + System.currenttimemillis (), "Content" +system.currenttimemillis (), Multiparts, "Reservation cancellation", "1872", "Test"); Long end = System.currenttimemillis (); Thread.Sleep (5000000); System.out.println ("Number of messages:" + size + ", total time consuming:" + (End-start)); } @Test public void Testmailsend () throws interruptedexception{ String sendmailaddr = "Kuangzhongwei@1872.net"; String sendmailpwd = "XXX"; list<string> transmitmails = new arraylist<string> (); Transmitmails.add ("kuangzhongwei@gmail.com");
list<string> takemail = new arraylist<string> (); Takemail.add ("346554535@qq.com"); SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String subject = Sdf.format (new Date ()) + "subject"; String content = Sdf.format (new Date ()) + Content Chinese contents;
HTML code attention encoding /*file f = new File ("G:\a.txt"); BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream (f))); System.out.println (New InputStreamReader (new FileInputStream (f)). GetEncoding ()); String filecontent = null; while (null!= (filecontent = In.readline ())) { Content + + filecontent; } In.close (); */ list<string> multiparts = new arraylist<string> (); Multiparts.add ("G:/a.txt");
New Mailserviceimpl (). SendMail (Sendmailaddr, Sendmailpwd, Transmitmails, Takemail, subject, content, Multiparts, "02", "1872", "Test"); Thread.Sleep (200000); } } WebServices Configuration <!--Mail Web service configuration--> <service> <name>mail</name> <namespace>http://com.reagle</namespace> <serviceClass>com.reagle.server.IMailService</serviceClass> <implementationClass> Com.reagle.server.impl.MailServiceImpl </implementationClass> </service> WebService Client Invocation /** * */ Package com.reagle.test;
Import Java.text.SimpleDateFormat; Import java.util.ArrayList; Import Java.util.Date; Import java.util.List;
Import Org.junit.Before; Import Org.junit.Test;
Import reagle.com.ArrayOfString;
/** * @Program Name:testMailClient.com.reagle.test.TestMailServiceClient.java * @Written BY:KZW * @version: v1.00 * @Creation date:2012-7-18 05:00:47 * @Description: * * @ModificationHistory who What------------------------------------- * KZW 2012-7-18 PM 05:00:47 Create * **/ public class Testmailserviceclient { Private Mailclient serivce; List<string> transmitmails; List<string> Takemail; List<string> Multiparts; @Before public void Testinit () { Serivce = new Mailclient (); Transmitmails = new arraylist<string> (); Takemail = new arraylist<string> (); Multiparts = new arraylist<string> (); Takemail.add ("100086@qq.com");
}
@Test public void Testmailsend () { SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String subject = Sdf.format (new Date ()) + "subject"; String content = Sdf.format (new Date ()) + Content Chinese contents; String sendmailaddr = "Kuangzhongwei@1872.net"; String sendmailpwd = "XXXXX"; Arrayofstring ccs=new arrayofstring (); Arrayofstring tos=new arrayofstring (); Arrayofstring multipartss=new arrayofstring (); Tos.getstring (). AddAll (Takemail);
Serivce.getmailhttpport (). SendMail (NULL, NULL, CCS, TOS, Subject, Content, MULTIPARTSS, "02", "1872", "Test");
} } |