The example in this article describes the Java implementation method for sending mail based on SMTP. Share to everyone for your reference. The implementation method is as follows:
Import Java.util.Date;
Import java.util.Properties;
Import Javax.mail.Authenticator;
Import Javax.mail.Message;
Import javax.mail.PasswordAuthentication;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;
Import Org.apache.log4j.Logger;
public class Mailutil {private static Logger Logger = Logger.getlogger (Mailutil.class);
/** * Send mail * * @param SMTP * SMTP server * @param user name * @param password * password * @param subject * Title * @param content * Mail contents * @param from * sender's mailbox * @param to * recipient mailbox/public static void send (String SMTP, final string user, final string password, string subject, string content, string from, string to)
{try {Properties props = new properties ();
Props.put ("Mail.smtp.host", SMTP);
Props.put ("Mail.smtp.auth", "true"); Session SSN = session.getinstance (props, New Authenticator () {@Override protecteD passwordauthentication getpasswordauthentication () {Return to new passwordauthentication (user, password);
}
});
MimeMessage message = new MimeMessage (SSN);
A new Message object is created by a mail session internetaddress fromaddress = new internetaddress (from);
Sender's email address message.setfrom (fromaddress);
Set Sender internetaddress toaddress = new internetaddress (to);
The recipient's mailing address message.addrecipient (Message.RecipientType.TO, toaddress);
Set recipient Message.setsubject (subject);
Set the title Message.settext (content);
Set content Message.setsentdate (new Date ());
Set the sending time transport transport = Ssn.gettransport ("SMTP");
Transport.connect (SMTP, user, password);
Transport.sendmessage (message, message. Getrecipients (Message.RecipientType.TO));
Transport.send (message);
Transport.close ();
Logger.info ("Mail sent successfully");
catch (Exception e) {logger.warn ("Send Mail Failed", e);
}
}
}
I hope this article will help you with your Java programming.