Not much to say, directly on the code
/** * Send mail * @param subject topics * @param to recipient * @ param username email account * @param password email password * @param host Mail server * @param content message content * @param isAuth Verify password */public Void send (string subject, string to,string username, string password, String host, string content,boolean isauth) {try{String[] mailArray = To.split (";"); /Multiple Recipients Internetaddress[] addresses = new internetaddress[mailarray.length];for (int i=0 ; i<mailarray.length;i++) {addresses[i] = new internetaddress (mailarray[i]);} Create properties to generate the Sessionproperties properties = new properties ();p roperties.put (" Mail.smtp.host ", host); //the host that sent the message properties.put (" Mail.smtp.auth ", isauth); // Whether to verify sender password PropertieS.put ("Mail.smtp.port", 25); //port//through configuration file, generate a sessionsession Mailsession = session.getinstance (Properties,null); mailsession.setdebug (true);// Start creating Messagemimemessage mailmessage = new mimemessage (MailSession) by session; /// /set sender, use Internetaddressmailmessage.setfrom (new internetaddress (username)); //recipient, Here are multiple mailmessage.setrecipients (mimemessage.recipienttype.to, addresses); Mailmessage.setsubject (subject); //Mail Subject //multipart is used to prevent the contents of the message, which can put multiple bodypart multipart multipart = new Mimemultipart (); //the first bodypart, place the ordinary text bar bodypart contentpart = new mimebodypart (); Contentpart.setcontent (content, "Text/html;charset=utf-8"); multipart.addbodypart (ContentPart); //the second bodypart, place the accessory bar BodyPart Attachmentbodypart = new mimebodypart (); //attachment file, need to use DataSource to construct object datasource source = new Filedatasource ("E:/students.xls"); //datasource need to use DataHandler to construct attachmentbodypart.setdatahandler (New datahandler (source)); attachmentbodypart.setfilename ("Students.xls");//attachment file name multipart.addbodypart (Attachmentbodypart); mailmessage.setcontent (multipart); //set the content to Messagemailmessage.setsentdate (new Date ()); //send time mailmessage.savechanges (); if (Isauth) {transport.send (Mailmessage, username, password) ;} Else{transport.send (mailmessage); //transport Start sending mail}}catch (exception e) {try {throw e ;} catch (EXCEPTION&NBSP;E1) {// TODO Auto-generated catch Blocke1.printstacktrace ();} E.printstacktrace ();}}
Simply write a Main method
public static void Main (String arg[]) {Mail mail = new mail ();//subject, recipient, sender, password, mail server .... Mail.send ("Test 1", "[email protected]", "[email protected]", "123456", "mail.chinacache.com", "TESTDFDF", false);}
This article is from the "Bulajunjun" blog, make sure to keep this source http://5148737.blog.51cto.com/5138737/1587624
Java Send mail