ImportJava.io.File;ImportJava.net.URL;ImportOrg.apache.commons.mail.Email;Importorg.apache.commons.mail.EmailAttachment;Importorg.apache.commons.mail.EmailException;ImportOrg.apache.commons.mail.HtmlEmail;ImportOrg.apache.commons.mail.MultiPartEmail;ImportOrg.apache.commons.mail.SimpleEmail; Public classSendMail {/*** Use Apache Commons email component (commons-email-1.4) to send mail * *@paramargs *@throwsException*/ Public Static voidMain (string[] args)throwsException {//Simplemail ();Sendhtmlmail ();//Sendattachmentmail (); } Public voidSimplemail () {Email email=NewSimpleemail (); Email.sethostname ("Smtp.test.com"); Email.setsmtpport (25); Email.setauthentication ("[Email protected]", "admin123"); Email.setsslonconnect (true); Try{Email.setfrom ("[Email protected]"); Email.setsubject ("Testmail"); Email.setmsg ("This is a test mail ...:-)"); Email.addto ("[Email protected]"); Email.send (); } Catch(emailexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Private Static voidSendhtmlmail ()throwsexception{//Create the email messageHtmlemail email =NewHtmlemail (); Email.sethostname ("Smtp.test.com"); Email.setsmtpport (25); Email.setauthentication ("[Email protected]", "password");//user name, passwordEmail.setsslonconnect (true); Email.addto ("[Email protected]", "Ken"); Email.addto ("[Email protected]");//Set RecipientEmail.setfrom ("[Email protected]", "Me"); Email.setsubject ("Test HTML Email"); //embed the image and get the content IDURL url =NewURL ("Http://qq.test.com/images/111.png"); String CID= email.embed (URL, "Qhcaifu logo"); //set the HTML messageEmail.sethtmlmsg ("); //Set the alternative messageEmail.settextmsg ("Your email client does not support HTML messages"); //Send the emailEmail.send (); } Private Static voidSendattachmentmail () {multipartemail email=NewMultipartemail ();//If you want to send a message with an attachment, you need to use this classEmail.sethostname ("Smtp.test.com"); Email.setauthentication ("[Email protected]", "admin123"); Email.setcharset ("UTF-8"); Try{Email.setfrom ("[Email protected]");//Set SenderEmail.addto ("[email protected]");//Set RecipientEmail.setsubject ("Test Mail");//Set ThemeEmail.setmsg (test mail test mail test message);//set up message contentFile File=NewFile ("C:\\testemail.txt");//attachments to sendemailattachment Attachment=Newemailattachment (); Attachment.setpath (File.getpath ()); Attachment.setname (File.getname ()); Attachment.setdescription ("Attachment description"); Attachment.setdisposition (emailattachment.attachment);//type of attachmentEmail.attach (attachment); Email.send (); System.out.println ("Sent successfully"); } Catch(emailexception e) {e.printstacktrace (); } }}
-------The required jar packages:
-------Exception Resolution:
Java Send mail Demo