PackageJavasocket;ImportJava.util.*;ImportJavax.mail.*;Importjavax.mail.internet.*; Public classEmail {/** ?????? */ PrivateString from; /** ?????? */ PrivateString to; /** ???? */ PrivateString subject; /** ???? */ PrivateString body; PublicEmail () {}/** * ???????. * @returnboolean-?????? */ Public BooleanSendMail () {if(GetBody () = =NULL|| Getto () = =NULL|| Getfrom () = =NULL|| Getsubject () = =NULL) {return false; } Try{Properties props=NewProperties (); Props.put ("Username", "[email protected]"); Props.put ("Password", "aa892475"); Props.put ("Mail.transport.protocol", "SMTP" ); Props.put ("Mail.smtp.host", "smtp.163.com"); Props.put ("Mail.smtp.port", "25" ); Session mailsession=session.getdefaultinstance (props); Message msg=Newmimemessage (mailsession); Msg.setfrom (Newinternetaddress (Getfrom ())); Msg.addrecipients (Message.RecipientType.TO, internetaddress. Parse (Getto ())); Msg.setsentdate (NewDate ()); Msg.setsubject (Getsubject ()); Msg.settext (GetBody ()); Msg.savechanges (); System.out.println ("?????????????????????"); Transport Transport= Mailsession.gettransport ("SMTP"); Transport.connect (Props.getproperty ("Mail.smtp.host"), props. GetProperty ("username"), Props.getproperty ("password"))); System.out.println ("??????????????????"); Transport.sendmessage (MSG, msg.getallrecipients ()); Transport.close (); System.out.println ("??????????????"); } Catch(Exception e) {e.printstacktrace (); System.out.println (e); return false; } return true; } /** * @returnReturns the body. */ PublicString GetBody () {returnbody; } /** * @paramBody * The body to set. */ Public voidSetbody (String body) { This. BODY =body; } /** * @returnReturns the From. */ PublicString Getfrom () {returnFrom ; } /** * @paramFrom -to set. */ Public voidSetfrom (String from) { This. from =From ; } /** * @returnReturns the subject. */ PublicString Getsubject () {returnsubject; } /** * @paramSubject * The subject to set. */ Public voidSetsubject (String subject) { This. Subject =subject; } /** * @returnReturns the To. */ PublicString Getto () {returnto ; } /** * @paramTo a to set. */ Public voidSetto (String to) { This. to =to ; } Public Static voidMain (string[] args) {Email sender=NewEmail (); Sender.setfrom ("[Email protected]"); Sender.setto ("[Email protected]"); Sender.setsubject ("???????"); Sender.setbody ("?????????????!"); Sender.sendmail (); }}
Java Send mail