Java implementation Simple Mail send _java

Source: Internet
Author: User
Tags constant

Java Mail is the use of existing mail accounts to send mail tools, for example, I registered in NetEase a mailbox account, through the control of Java mail, I can not personally login NetEase mailbox, so that the program automatically use NetEase mailbox to send mail. This mechanism is widely used in the field of registration activation and the sending of spam messages.
The approximate process for sending a Java message is this:

1. Build a concrete class that inherits from Javax.mail.Authenticator and rewrite the Getpasswordauthentication () method inside. This class is used as a login checksum to ensure that you have the right to send mail to the mailbox.

2, the construction of a properties file, which holds the SMTP server address and other parameters.

3, through the construction of properties files and Javax.mail.Authenticator specific classes to create a javax.mail.Session. The session is created as if it were a login mailbox. The only thing left is the new mail.

4, the construction mail content, is generally the Javax.mail.internet.MimeMessage object, and assigns the sender, the addressee, the topic, the content and so on.

5, use the Javax.mail.Transport tool class to send mail.

Here is the code I encapsulate, and the comments are more detailed.

1, the first is to inherit from the javax.mail.Authenticator of a specific class. the Getpasswordauthentication () method is to build a Passwordauthentication object and return, a little convoluted design intent such as Java Mail, It may be that Javax.mail.Authenticator has provided us with additional security verification measures.

 package com.mzule.simplemail;
Import Javax.mail.Authenticator;
 
Import javax.mail.PasswordAuthentication; /** * Server Mailbox Login Verification * * @author mzule * */public class Mailauthenticator extends Authenticator {/** * username (Login mailbox
  ) */private String username;
 
  /** * Password/private String password; /** * Initialize Mailbox and password * * @param username mailbox * @param password Password/public mailauthenticator (String username,
  String password) {this.username = username;
  This.password = password;
  String GetPassword () {return password; } @Override protected Passwordauthentication getpasswordauthentication () {return new passwordauthentication (Usern
  AME, password);
  String GetUserName () {return username;
  } public void SetPassword (String password) {this.password = password;
  } public void Setusername (String username) {this.username = username; }
 
}

2, Mail send Class , and the rest of the steps are implemented in this class. The Simplemail in the code is a pojo that encapsulates the subject and content of the message. This method is overloaded because it is not appropriate to include both the subject and the content in a method parameter. And because most of the SMTP server addresses of mailboxes are available through the mailbox address, it is simple to provide a constructor that does not require an SMTP server address.

Package com.mzule.simplemail;
Import java.util.List;
 
Import java.util.Properties;
Import javax.mail.MessagingException;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.AddressException;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;
 
Import Javax.mail.internet.MimeMessage.RecipientType;
 /** * Simple Mail transmitter, can single, Mass. * * * * @author mzule * * */public class Simplemailsender {/** * props file to send mail * * * Private final transient Prop
  Erties props = System.getproperties ();
 
  /** * Mail Server login Verification * * Private transient mailauthenticator authenticator;
 
  /** * Mailbox session/private transient session;
   /** * Initialize Mail transmitter * * @param smtphostname * SMTP mail server address * @param username * Email username (address)
    * @param password * Email password/public simplemailsender (final string smtphostname, final string username, Final String password) {init (username, password, sMtphostname);        /** * Initiates the Mail dispatcher * * @param username * The user name (address) of the sending message, and resolves the SMTP server address * @param password *
  The password to send the message/public Simplemailsender (final string username, final string password) {//resolves the SMTP server through the mailbox address, which works for most mailboxes
  Final String smtphostname = "smtp." + Username.split ("@") [1];
 
  Init (username, password, smtphostname); /** * Initialization * * @param username * Email username (address) * @param password * password * @param SMT Phostname * SMTP Host address */private void init (string username, string password, string smtphostname) {//initialization
  Props Props.put ("Mail.smtp.auth", "true");
  Props.put ("Mail.smtp.host", smtphostname);
  Verify authenticator = new Mailauthenticator (username, password);
  Create Session session = Session.getinstance (props, authenticator); /** * Send mail * * @param recipient * Recipient email address * @param subject * Mail subject * @param conte NT * Mail content * @throws ADdressexception * @throws messagingexception */public void Send (string recipient, string subject, Object content) 
  Throws Addressexception, Messagingexception {//create MIME type mail final mimemessage message = new MimeMessage (session);
  Set the sender Message.setfrom (new internetaddress (Authenticator.getusername ()));
  Set recipient Message.setrecipient (Recipienttype.to, New InternetAddress (recipient));
  Set subject Message.setsubject (subject);
  Set the content of the message message.setcontent (content.tostring (), "text/html;charset=utf-8");
  Send transport.send (message);
   /** * Mass Mailing * * @param recipients * Recipients * @param subject * Subject * @param content * Content * @throws addressexception * @throws messagingexception/public void Send (List<string> re Cipients, String subject, Object content) throws Addressexception, Messagingexception {//create MIME type mail final mimeme
  Ssage message = new MimeMessage (session); Set Sender message.seTfrom (New InternetAddress (Authenticator.getusername ()));
  Set recipient final int num = Recipients.size ();
  Internetaddress[] addresses = new Internetaddress[num];
  for (int i = 0; i < num i++) {addresses[i] = new InternetAddress (Recipients.get (i));
  } message.setrecipients (recipienttype.to, addresses);
  Set subject Message.setsubject (subject);
  Set the content of the message message.setcontent (content.tostring (), "text/html;charset=utf-8");
  Send transport.send (message); /** * Send mail * * @param recipient * Recipient email address * @param mail * Mail Object * @throws addresses Exception * @throws messagingexception */public void Send (String recipient, Simplemail Mail) throws Addressex
  Ception, messagingexception {Send (recipient, Mail.getsubject (), mail.getcontent ()); /** * Mass Mailing * * @param recipients * Recipients * @param mail * Mail Object * @throws addressex Ception * @throws messagingexception/public void Send (List<string> recipients, Simplemail Mail) throws Addressexception, messagingexception {send (recipients, mail.get
  Subject (), mail.getcontent ());
 }
 
}

3, call the above mailbox transmitter, you can build a factory class , the factory class can encapsulate the process of creation, so read the configuration file to get the mailbox username, password will become very convenient. The following code was written while I was writing the observer pattern, just a simple demonstration of the factory class.

Package com.mzule.dp.observer.factory;
 
Import Com.mzule.dp.observer.constant.MailSenderType;
Import Com.mzule.simplemail.SimpleMailSender;
 
/** *
 Outbox Factory * * 
 @author mzule * */Public
class Mailsenderfactory {
 
  /**
   * Service mailbox
   *
  private static Simplemailsender servicesms = null;
 
  /**
   * Get Mailbox
   * 
   * @param type mailbox Types
   * @return compliant mailbox/public
  static Simplemailsender Getsender (Mailsendertype type) {
  if (type = = Mailsendertype.service) {
    if (servicesms = = null) {
    servicesms = new Simplemailsender ("invisible@126.com",
      "hidden");
    }
    return servicesms;
  }
  return null;
  }
 
}

4, send mail , or observer mode demo inside the code, shout.

Package com.mzule.dp.observer.observer;
Import java.util.ArrayList;
Import java.util.List;
Import java.util.Observable;
 
Import Java.util.Observer;
Import javax.mail.MessagingException;
 
Import javax.mail.internet.AddressException;
Import Com.mzule.dp.observer.constant.MailSenderType;
Import Com.mzule.dp.observer.factory.MailSenderFactory;
Import com.mzule.dp.observer.po.Product;
 
Import Com.mzule.simplemail.SimpleMailSender;
  public class Productpriceobserver implements Observer {@Override public void update (observable obj, Object Arg) {
  Product Product = NULL;
  if (obj instanceof product) {Product = (product) obj;
    } if (arg instanceof float) {Float price = (float) arg;
    Float decrease = Product.getprice ()-Price;
    if (Decrease > 0) {//send mail Simplemailsender SMS = mailsenderfactory. Getsender (Mailsendertype.service);
    list<string> recipients = new arraylist<string> ();
    Recipients.add ("invisible@qq.com"); RecipIents.add ("invisible@gmail.com");  try {for (String recipient:recipients) {sms.send (recipient, "Price change", "items you care about" + product.getname () + "Reduce the price, by" + product.getprice () + "yuan to" + "+" Yuan, the decline of "+ decrease +" yuan. Hurry up and go shopping.
      ");
    } catch (Addressexception e) {e.printstacktrace ();
    catch (Messagingexception e) {e.printstacktrace (); }
    }
  }
  }
 
}

5, to see if the message was sent successfully.
The above is the whole process of sending Java mail, I hope to help you learn.

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.