Send an email using javaMail
This article implements simple email sending.
Import java. util. date; import java. util. map; import java. util. properties; import javax. mail. address; 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; public class Sender {// enter the user name/password of the mailbox. You can configure private String username = [email protected] In a properties file; private String password = xxxxxxx; // here you can put an object in without using map public void send (Map map) throws Exception {/** create Properties object * set the connected mail service address * enable authentication */Properties props = new Properties (); // The email service qq is smtp.qq.com props. put (mail. smtp. host, smtp.163.com); // enable props verification. put (mail. smtp. auth, true);/** create a Session object from ProPerties and connect to the mail server * getDefaultInstance () * 1 Properties * 2 authentication object Authenticator */session Session = Session. getDefaultInstance (props, new Authenticator () {@ Override protected PasswordAuthentication getPasswordAuthentication () {// TODO Auto-generated method stub // verify the username and password return new PasswordAuthentication (username, password) ;}});/** defines the mail content object Message to put the session into */Message msg = new MimeMessage (session ); // define the sender Address from = new InternetAddress (String) map. get (from); msg. setFrom (from); // defines the recipient Address to = new InternetAddress (String) map. get (to); msg. setRecipient (Message. recipientType. TO, to);/* Address [] tos = new Address [3]; msg. setRecipients (Message. recipientType. TO, tos); * // defines the cc. If there are multiple cc recipients, you need an Address array Address cc = new InternetAddress (String) map. get (cc); msg. setRecipient (Message. recipientType. CC, cc); // set the topic msg. setSubject (String) map. get (subject);/** add mail content * setContent */msg. setContent (String) map. get (content), text/plain; charset = UTF-8); // sending time msg. setSentDate (new Date (); // Save the message msg. saveChanges (); // send the message Transport. send (msg );}}
Test:
Import java. util. hashMap; import java. util. map; import com. etoak. util. sender; public class Test {public static void main (String [] args) throws Exception {Map map = new HashMap (); map. put (from, [email protected]); map. put (to, [email protected]); map. put (cc, [email protected]); map. put (content, this is the mail content); map. put (subject, this is the topic); Sender sd = new Sender (); sd. send (map );}}
Test results: