Premise: Import a jar package that sends Java mail:
Activation.jar Additionnal.jar (third-party client, if not) Mail.jar
Additionnal.jar (third-party client, what path does not appear when the system file is not found)
Step one: Write the outgoing mail class
Package com.gl.util;
Import Java.util.Properties
Import javax.mail.*;
Import javax.mail.internet.*;
public class Mailutil {
Incoming email address and email activation code
public static void SendMail (String to,string code) {
The server that sent the message
String host = "smtp.qq.com";
User name
String username= "[email protected]";
Third-party client authentication password, need to open in QQ mailbox account/smtp/pop3/imap/SMTP/POP3
SMS get third-party client login authentication password
String password= "************";
Session Object
Properties Props = new properties ();
Props.put ("Mail.smtp.host", host);
Port number of the sending message
Props.put ("Mail.smtp.port", "465");
/* Props.put ("Mail.transport.protocol", "SMTP"); */
Props.put ("Mail.smtp.auth", "true");
Props.put ("Mail.smtp.ssl.enable", "true");///Use STARTTLS secure connection
Props.put ("Mail.debug", "true");
Session session = Session.getdefaultinstance (props);
Message Object
MimeMessage message = new MimeMessage (session);
Set Sender
try {
Message.setfrom (new internetaddress (username));
Set recipient
Message.setrecipients (message.recipienttype.to,to);
Set theme
Message.setsubject ("account activation email from Xionger Mall");
Set content
Message.setcontent ("
Message.savechanges (); Implicit with Send ()
Transport Transport = Session.gettransport ("SMTP");
Transport.connect (host, username, password);
Transport.sendmessage (Message, message.getallrecipients ());
Transport.close ();
} catch (Addressexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (Messagingexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}
Step two: Implement the class, call the method of sending the message (registration, etc.), this example is struts
Public String Reg () {
Usersserviceimpl usersserviceimpl= (Usersserviceimpl) Ac.getbean ("Usersservice");
Users.setu_state (FALSE);
String U_code = Uuid.randomuuid (). toString (). Replace ("-", "");
System.out.println (U_code);
System.out.println (Users.getu_email ());
Users.setu_code (U_code);
Usersserviceimpl.save (users);
Mailutil.sendmail (Users.getu_email (), U_code);
return "Regok";
}
Java Send mail