Java e-mail with attachment test passed

Source: Internet
Author: User

 PackageCn.bric.crm.util;Importjava.util.Date;Importjava.util.Enumeration;Importjava.util.Properties;ImportJava.util.Vector;Importjavax.activation.*;ImportJavax.mail.Authenticator;ImportJavax.mail.Message;ImportJavax.mail.Multipart;Importjavax.mail.PasswordAuthentication;Importjavax.mail.Session;ImportJavax.mail.Transport;Importjavax.mail.internet.InternetAddress;ImportJavax.mail.internet.MimeBodyPart;ImportJavax.mail.internet.MimeMessage;ImportJavax.mail.internet.MimeMultipart;Importjavax.mail.internet.MimeUtility;ImportJava.io.FileInputStream;Importjava.io.IOException;Importjava.text.ParseException;Importjava.util.ArrayList;Importjava.util.Date;ImportJava.util.HashSet;ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.Locale;ImportJava.util.Set;ImportJava.util.regex.Pattern;/*** <p> * Title: Send mail using JavaMail * </p>*/ Public classmailutils {String to= "";//RecipientString from = "";//SenderString host = "";//SMTP HostString username = ""; String Password= ""; String filename= "";//attachment file nameString subject = "";//Message SubjectString content = "";//message bodyVector file =NewVector ();//Attachment file Collection    /*** <br> * Method Description: Default constructor <br> * Input parameter: <br> * return type:*/     Publicmailutils () {}/*** <br> * Method Description: Constructor, provide direct parameter incoming <br> * Input parameters: <br> * return type:*/     Publicmailutils (String to, string from, String SmtpServer, string Username, string password, string subject, STR ing content) { This. to =to ;  This. from =From ;  This. Host =SmtpServer;  This. Username =username;  This. Password =password;  This. Subject =subject;  This. Content =content; }    /*** <br> * method Description: Set mail server address <br> * Input parameters: String host Mail server address name <br> * return type:*/     Public voidSethost (String host) { This. Host =host; }    /*** <br> * Method Description: Set the login server check password <br> * Input parameters: <br> * return type:*/     Public voidSetPassword (String pwd) { This. Password =pwd; }    /*** <br> * Method Description: Set the login server check user <br> * Input parameters: <br> * return type:*/     Public voidSetusername (String USN) { This. Username =USN; }    /*** <br> * method Description: Set Email destination mailbox <br> * Input parameters: <br> * return type:*/     Public voidSetto (String to) { This. to =to ; }    /*** <br> * Method Description: Set up mail sending source mailbox <br> * Input parameter: <br> * return type:*/     Public voidSetfrom (String from) { This. from =From ; }    /*** <br> * Method Description: Set message subject <br> * Input parameters: <br> * return type:*/     Public voidSetsubject (String subject) { This. Subject =subject; }    /*** <br> * Method Description: Set message contents <br> * Input Parameters: <br> * return type:*/     Public voidsetcontent (String content) { This. Content =content; }    /*** <br> * Method Description: Convert the theme to Chinese <br> * Input parameters: String strText <br> * return type:*/     Publicstring Transferchinese (String strText) {Try{StrText= Mimeutility.encodetext (NewString (Strtext.getbytes (),"GB2312"), "GB2312", "B"); } Catch(Exception e) {e.printstacktrace (); }        returnStrText; }    /*** <br> * Method Description: Add Accessories <br> * Input parameters: <br> * return type to the attachment combination :*/     Public voidattachfile (String fname) {file.addelement (fname); }    /*** <br> * method Description: Send mail <br> * Input parameters: <br> * return Type: Boolean success is true, reverse is false*/     Public BooleanSendMail () {//Construct mail SessionProperties props =NewProperties (); Props.put ("Mail.smtp.host", host); Props.put ("Mail.smtp.auth", "true"); Session Session=session.getdefaultinstance (Props,NewAuthenticator () { Publicpasswordauthentication getpasswordauthentication () {return Newpasswordauthentication (username, password);        }                }); //Session session = Session.getdefaultinstance (props);//Session session = Session.getdefaultinstance (props, null);        Try {            //constructs a mimemessage and sets a basic valueMimeMessage msg =NewMimeMessage (session); //mimemessage msg = new MimeMessage ();Msg.setfrom (Newinternetaddress (from)); //msg.addrecipients (Message.RecipientType.TO, address);//This can only be sent to a single person emailmsg.setrecipients (Message.RecipientType.BCC, Internetaddress.parse (to)); Subject=Transferchinese (subject);            Msg.setsubject (subject); //Construction MultipartMultipart MP =NewMimemultipart (); //add body to multipartMimeBodyPart mbpcontent =NewMimeBodyPart (); Mbpcontent.setcontent (Content,"text/html;charset=gb2312"); //Add to MimeMessage (multipart representative body)Mp.addbodypart (mbpcontent); //add an attachment to a multipartEnumeration efile =file.elements ();  while(Efile.hasmoreelements ()) {MimeBodyPart Mbpfile=NewMimeBodyPart (); FileName=efile.nextelement (). toString (); Filedatasource FDS=Newfiledatasource (filename); Mbpfile.setdatahandler (NewDataHandler (FDS)); <span style= "color: #ff0000;" >//This method can solve the attachment garbled problem. </span>String filename=NewString (Fds.getname (). GetBytes (), "Iso-8859-1");                Mbpfile.setfilename (filename); //Add to MimeMessage (multipart on behalf of attachment)Mp.addbodypart (Mbpfile);            } file.removeallelements (); //add MimeMessage to multipartMsg.setcontent (MP); Msg.setsentdate (NewDate ());            Msg.savechanges (); //Send mailTransport Transport= Session.gettransport ("SMTP");            Transport.connect (host, username, password);            Transport.sendmessage (MSG, msg.getallrecipients ());        Transport.close (); } Catch(Exception Mex) {mex.printstacktrace ();//Exception ex = null;//if (ex = Mex.getnextexception ()) = null) {//ex.printstacktrace ();//            }            return false; }        return true; }        /*** <br> * Method Description: Main method, for testing <br> * Input parameters: <br> * return type:*/      Public Static voidMain (string[] args) {mailutils sendmail=Newmailutils (); Sendmail.sethost ("Smtp.qiye.163.com"); Sendmail.setusername ("[Email protected]"); Sendmail.setpassword ("XXXXXX"); Sendmail.setto ("[Email protected]accfutures.com,[email protected],[email protected]"); Sendmail.setfrom ("[Email protected]"); Sendmail.setsubject ("Hello, this is the test!" "); Sendmail.setcontent ("Hello this is a test with multiple attachments!" "); //Mail sendmail = new//Mail ("[Email protected]", "[email protected]", "smtp.sohu.com", "Du_jiang", "31415926", "hello", "stomach, how are you?" ");Sendmail.attachfile ("D:\\news.rar"); Sendmail.attachfile ("D:\\jhjl.rar");     System.out.println (Sendmail.sendmail ()); }}

Original: Http://chengyue2007.iteye.com/blog/787151#comments

Java sends a message with an attachment test through

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.