Java Web Mail Sending and receiving

Source: Internet
Author: User
Tags email account

1. Online method to import two packages

Mail.jar&activation.jar
 PackageCom.zjh.shopping.util;Importjava.util.Date; Importjava.util.Properties; ImportJavax.activation.DataHandler; ImportJavax.activation.FileDataSource; ImportJavax.mail.Authenticator; ImportJavax.mail.Multipart; Importjavax.mail.PasswordAuthentication; Importjavax.mail.internet.InternetAddress; ImportJavax.mail.internet.MimeBodyPart; ImportJavax.mail.internet.MimeMultipart; Importjavax.mail.internet.MimeUtility;  Public classJavamailsendutil { Public  voidSendMail (string subject, String from, string[] to, string text, string[] filenames, string mimeType) { Try{Properties props=NewProperties (); String SMTP= "smtp.163.com";//set the SMTP used to send mailString servername = "*******";//Email account nameString serverpaswd = "******";//Email Passwordjavax.mail.Session mailsession=NULL;//Mail Session ObjectJavax.mail.internet.MimeMessage mimemsg =NULL;//MIME Message ObjectProps= Java.lang.System.getProperties ();//Get System Property ObjectProps.put ("Mail.smtp.host", SMTP);//setting up an SMTP hostProps.put ("Mail.smtp.auth", "true");//whether to server user name and password Authentication//to the server to verify that the user name and password sent are correctSmtpauthenticator Myemailauther =NewSmtpauthenticator (servername, SERVERPASWD); //set up a mail session note here The authentication information is placed in the session's creation parametersMailSession =javax.mail.Session.getInstance (props, (Authenticator) myemailauther); //set up the transport protocolJavax.mail.Transport Transport = Mailsession.gettransport ("SMTP"); //set up information from, to, etc.Mimemsg =Newjavax.mail.internet.MimeMessage (mailsession); if(NULL! = from &&! "". Equals (from)) {internetaddress Sentfrom=Newinternetaddress (from); Mimemsg.setfrom (Sentfrom); //set up sender address} internetaddress[] SendTo=NewInternetaddress[to.length];  for(inti = 0; i < to.length; i++) {System.out.println ("Send to:" +To[i]); Sendto[i]=Newinternetaddress (To[i]);             } mimemsg.setrecipients (Javax.mail.internet.MimeMessage.RecipientType.TO, sendTo); Mimemsg.setsubject (Subject,"GB2312"); MimeBodyPart MessageBodyPart1=NewMimeBodyPart (); //Messagebodypart.settext (Unicodetochinese (text)); messagebodypart1.setcontent (text, mimeType); //Attachment transfer FormatMultipart Multipart =NewMimemultipart ();              Multipart.addbodypart (MESSAGEBODYPART1);  for(inti = 0; i < filenames.length; i++) {MimeBodyPart MessageBodyPart2=NewMimeBodyPart (); String filename= Filenames[i].split (";") [0]; String DisplayName= Filenames[i].split (";") [1]; //get the data sourceFiledatasource FDS =Newfiledatasource (filename); //bodypart adding attachments themselvesMessagebodypart2.setdatahandler (NewDataHandler (FDS)); //bodypart Adding an attachment file namemessagebodypart2.setfilename (mimeutility. Encodetext (displayname));             Multipart.addbodypart (MESSAGEBODYPART2);             } mimemsg.setcontent (multipart); //set the sending date of the letter headerMimemsg.setsentdate (NewDate ());             Mimemsg.savechanges (); //Send mailtransport.send (mimemsg);             Transport.close (); System.out.println ("Send To Success!!!"); } Catch(Exception e) {e.printstacktrace (); }     }           Public Static voidMain (string[] args)throwsException {String title= "Test Mail";//The title of the sent messageString from = "************@163.com";//Send from thereString sendto[] = {"******** @qq. com"};//sent to There//the text content of the message, which can contain HTML tags, is displayed as an HTML pageString content = "Test java Send mail!!!!!! <br><a href= "http://sjsky.javaeye.com/">my blog</a>"; //The included attachments, and the rename of the attachmentsString filenames[] = {"D:\\test.jpg;test.jpg" }; Javamailsendutil Test=NewJavamailsendutil (); Try {           //MailSender MailSender = new MailSender (); Test.sendmail (title, from, SendTo, content, FileNames,"text/html;charset=gb2312"); } Catch(Exception ex) {ex.printstacktrace (); }   }      classSmtpauthenticatorextendsAuthenticator {String username=NULL; String Password=NULL;  PublicSmtpauthenticator (string Username, string password) {Super();  This. Username =username;  This. Password =password; }              Publicpasswordauthentication getpasswordauthentication () {return NewPasswordauthentication ( This. Username, This. Password); }     }  }  

2. Self-use

 PackageCom.gree.mail.mailsend;Importjava.util.Properties;ImportJavax.mail.Message;Importjavax.mail.Session;ImportJavax.mail.Transport;Importjavax.mail.internet.InternetAddress;ImportJavax.mail.internet.MimeMessage;ImportJavax.naming.InitialContext;Importjavax.naming.NamingException;Importcom.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException; Public classMailsend2 { Public Staticsession getsession () {Session session=NULL; //Session = (session) New InitialContext (). Lookup ("MailSession");Properties Props=NewProperties (); Props.put ("Mail.smtp.host", "10.1.1.168"); Props.put ("Mail.smtp.auth", "false"); Session= Session.getdefaultinstance (Props,NULL); returnsession;} Public Static voidsendMessage (string from, string[) to, string[] cc, string subject, string content, St Ring MimeType)throwsjavax.mail.MessagingException {Message message=NewMimeMessage (GetSession ()); if(!Stringutils.isempty (from)) {internetaddress Sentfrom=Newinternetaddress (from);    Message.setfrom (Sentfrom); } internetaddress[] SendTo=NewInternetaddress[to.length];  for(inti = 0; i < to.length; i++) {Sendto[i]=NewInternetAddress (to[i]+ "@gree. com.cn"); }    if((Cc.length > 0) && (cc[0]! =NULL) ) {internetaddress[] copyTo=NewInternetaddress[cc.length];  for(inti = 0; i < cc.length; i++) {Copyto[i]=NewInternetAddress (cc[i]+ "@gree. com.cn");    } message.setrecipients (Message.RecipientType.CC, copyTo);    } message.setrecipients (Message.RecipientType.TO, sendTo); //System.out.println ("Sending Person:" +message.getrecipients (Message.RecipientType.TO)); //System.out.println ("CC Person:" +message.getrecipients (Message.RecipientType.CC))Message.setsubject (subject);    Message.setcontent (content, MimeType); Transport.send (message); }  Public voidSendhtmlmessage (string[] to, string[] cc, string title, string content)throwsmessagingexception {Try{sendMessage ("Scbweb", To, CC, title+ "-Mold management System Information", content, "text/html; charset=gb2312 "); } Catch(javax.mail.MessagingException e) {//TODO auto-generated Catch blockE.printstacktrace (); }         //System.out.println ("2=" +content);} Public Static voidMain (string[] args) {String [] to=NewString[] {"180172"}; String [] cc=NewString[] {"180158"}; String title= "Ceshi"; String content= "Please let us eat grilled fish at night, opposite Gate 8th, about 67 o ' clock.; Try{mailsend2.sendmessage ("[Email protected]", to, CC, title, content, "text/html; Charset=utf-8 "); } Catch(javax.mail.MessagingException e) {//TODO auto-generated Catch blocke.printstacktrace ();} }}
MyEclipse Send message appears exception in thread "main" Java.lang.noclassdeffounderror:com/sun/mail/util/lineinputstream

This problem occurs because the jar package version is not uniform and the workaround is as follows:
I imported the jar package in the project

Conflicts with MyEclipse's own jar

Delete the package in Java EE 5 Libraries/javaee.jar/mail there is something.

Specific operation:

Enter the installation directory for MyEclipse: I installed the myeclipse Blue 8.5 specific path as follows

E:\development_tools\myeclipse_8.5\install_d\common\plugins\com.genuitec.eclipse.j2eedt.core_8.5.0. Me201003231033\data\libraryset\ee_5

Find Javaee.jar, open and delete the Mail folder (you need to close the running MyEclipse, otherwise you cannot delete)

Java Web Mail Sending and receiving

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.