Java packaged mail package send email class _java

Source: Internet
Author: User
Tags auth getmessage sessions

The following code encapsulates a class that sends messages using a Java Mail package

Import Java.io.File;
Import java.util.ArrayList;
Import Java.util.Date;
Import java.util.List;

Import java.util.Properties;
Import Javax.activation.DataHandler;
Import Javax.activation.FileDataSource;
Import Javax.mail.Message;
Import javax.mail.MessagingException;
Import Javax.mail.Multipart;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.AddressException;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeBodyPart;
Import Javax.mail.internet.MimeMessage;

Import Javax.mail.internet.MimeMultipart; public class SendMail {private static final String Mail_address_regex = "^[\\w\\.=-]+@[\\w\\.-]+\\.[

  \\w]{2,3}$ ";
  Private String mailserver;
  Private String sender;

  Private string[] receiver; Public SendMail () {} public void Setmailbasicinfo (String mailserver,string sender,string receiver) {This.mailser
    ver = mailserver;
    This.sender = sender;
  This.receiver =receiver.split (","); } public void SetmaiLbasicinfo (String mailserver,string sender,string[] users) {this.mailserver = MailServer;
    This.sender = sender;
  This.receiver = users; } public void Setmailbasicinfo (String mailserver,string sender,list<string> users) {this.mailserver = Mailser
    Ver
    This.sender = sender;
    This.receiver = new String[users.size ()];
  Users.toarray (This.receiver); public boolean send (string subject, string content, list<string> fileNames) {subject = Subject==null? ""
    : Subject;
    Content = Content==null? "": Content;
    Properties Props = new properties ();
    Props.put ("Mail.smtp.host", mailserver);
    Session session = Session.getinstance (props, null);
      try {internetaddress[] receiver = getreceiverlist ();
        if (Receiver.length = = 0) {System.out.println ("receiver is null");
      return false;
      MimeMessage msg = new MimeMessage (session);
      Msg.setfrom (new InternetAddress (sender)); Msg.setrecipiEnts (Message.RecipientType.TO, receiver);
      Msg.setsubject (subject);

      Msg.setsentdate (New Date ());
      Multipart container = new Mimemultipart ();
      MimeBodyPart Textbodypart = new MimeBodyPart ();
      Textbodypart.setcontent (Content.tostring (), "TEXT/HTML;CHARSET=GBK");

      Container.addbodypart (Textbodypart);
      Doattachfile (Container,filenames);
      Msg.setcontent (container);
      SYSTEM.OUT.PRINTLN ("Begin Send Mail");
      Transport.send (msg);
    SYSTEM.OUT.PRINTLN ("Send mail Success");
      catch (Messagingexception e) {System.out.println ("Send mail Fail");
      System.out.println (e);
    return false;
    catch (Exception e) {return false;
  return true;
  public boolean send (string subject, string content) {return send (subject,content,null);
  public boolean send (String subject) {return send (subject,null); private void Doattachfile (Multipart container, list<string> fileNames) throws messagingexception{if (filenames==null | | | filenames.size () ==0) return;
      for (String filename:filenames) {file F = new file (filename);
      if (!f.isfile ()) continue;
      System.out.println ("The Attach file is:" +filename);
      MimeBodyPart Filebodypart = new MimeBodyPart ();
      Filedatasource FDS = new Filedatasource (f);//The attachment address to send Filebodypart.setdatahandler (new DataHandler (FDS));
    Filebodypart.setfilename (Fds.getname ());//Set the name of the attachment Container.addbodypart (Filebodypart); } private internetaddress[] Getreceiverlist () throws addressexception {arraylist<internetaddress> toLi
    st = new Arraylist<internetaddress> (); for (int i = 0; i < receiver.length ++i) {if (Receiver[i].matches (Mail_address_regex)) {Toli
      St.add (New InternetAddress (receiver[i));
  } return (internetaddress[]) Tolist.toarray (new Internetaddress[tolist.size ()));

 }
}

Use examples

String host = "168.xx.xx.xx"; Mail server address
String subject = "Subject of Send Message";
String sender = "test@gmail.com";
list<string> receivers = new arraylist<string> ();
Receivers.add ("user1@263.com");
Receivers.add ("user2@263.com");
String content = "message subject";
SendMail SendMail = new SendMail ();
Sendmail.setmailbasicinfo (host, sender, receivers);
Sendmail.send (subject, content, NULL); No attachments

The body can also be HTML content, such as

String content = " 
 

Let's take another look at a packaged class

Package com.message.base.email;
Import Com.message.base.spring.ApplicationHelper;
Import Com.message.base.utils.StringUtils;
Import Com.message.base.utils.ValidateUtils;
Import Org.slf4j.Logger;
 
Import Org.slf4j.LoggerFactory;
Import javax.mail.*;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;
Import java.util.Collections;
Import Java.util.Date;
Import java.util.List;
 
Import java.util.Properties;
 /** * Send mail server. * * @author Sunhao (sunhao.java@gmail.com) * @version V1.0, 13-3-25 morning 6:19 * * public class Emailserver {private Stati
  C final Logger Logger = Loggerfactory.getlogger (Emailserver.class);
  In spring, configure the/** Mailbox server configuration **/private list<emailconfig> config;
  /** whether debug debug mode is turned on **/private Boolean isdebug = false;
  /** whether to enable authentication **/Private Boolean Isauth = true;
 
  /** Authentication type **/private String authtype = "Auth"; /** * Privatization default constructor, so that the external cannot be instantiated/private Emailserver () {}/** * single case, guarantee only one emailserver in context * * @return EmAilserver */public static Emailserver getinstance () {return applicationhelper.getinstance (). Getbean (Emailserver.
  Class);
   /** * Send ordinary Mail (single receiver) * * @param username sender username * @param password sender password * @param title Message title * @param content message body * @param receiver Single Receiver * @return/public boolean sendtextmail (String username, S Tring Password, string title, string content, string receiver) {return This.sendtextmail (username, password, title, CO
  Ntent, Collections.singletonlist (receiver));
   /** * Send ordinary mail (multiple recipients) * * @param username sender username * @param password sender password * @param title Message title * @param content Message body * @param receivers multiple Receivers * @return/public boolean sendtextmail (String username,
    String password, string title, string content, list<string> receivers) {authentication auth = null; if (This.isauth ()) {//If authentication is required, create a password validator auth = new authentication (username, password);
    Properties Props = new properties (); Props.setproperty ("Mail.smtp.auth", This.isauth)?
    "True": "false");
    Props.setproperty ("Mail.transport.protocol", "auth");
    Emailconfig config = this.getemailconfig (username);
    Props.setproperty ("Mail.smtp.host", Config.getsmtp ());
 
    Props.setproperty ("Mail.smtp.port", Config.getport () + "");
    Constructs a session sessions that send a message, based on message conversation properties and password validators = session.getdefaultinstance (props, auth);
 
    Session.setdebug (This.isdebug);
    Message message = This.maketextmail (session, title, content, username, receivers, false);
 
      try {transport.send (message);
    return true;
      catch (Messagingexception e) {logger.error (E.getmessage (), E);
    return false; /** * Send HTML message (single receiver) * * @param username sender username * @param password sender password * @param title Item Title * @param Content message body * @param receiver Single Receiver * @return/public boolean sendhtmlmail (StringUsername, string password, string title, string content, string receiver) {return This.sendhtmlmail (username, password
  , title, content, Collections.singletonlist (receiver);
   /** * Send HTML mail (multiple recipients) * * @param username sender username * @param password sender password * @param title Message title * @param content Message body * @param receivers multiple Recipients * @return/public boolean sendhtmlmail (String username
    , string password, string title, string content, list<string> receivers) {authentication auth = null;
    if (This.isauth ()) {//If authentication is required, create a password validator auth = new authentication (username, password);
    Properties Props = new properties (); Props.setproperty ("Mail.smtp.auth", This.isauth)?
    "True": "false");
    Props.setproperty ("Mail.transport.protocol", "auth");
    Emailconfig config = this.getemailconfig (username);
    Props.setproperty ("Mail.smtp.host", Config.getsmtp ()); Props.setproperty ("Mail.smtp.port", Config.getport () + "");
 
    Constructs a session sessions that send a message, based on message conversation properties and password validators = session.getdefaultinstance (props, auth);
 
    Session.setdebug (This.isdebug);
    Message message = This.maketextmail (session, title, content, username, receivers, true);
 
      try {transport.send (message);
    return true;
      catch (Messagingexception e) {logger.error (E.getmessage (), E);
    return false; /** * Get mail server configuration * * @param email Email address * @return/private emailconfig Getemailconfig (Strin
    G email) {String Mailservicedomainname = this.getmailservicedomainname (email);
      for (Emailconfig config:this.config) {if (Config.getname (). Equals (Mailservicedomainname)) {return config;
  } return null; /** * Create message messages * * @param session based on configuration @param title message subject * @param content message Content * @param from Sender * @param receivers recipient * @param ishtmlmail is HTML mail/private message MakEtextmail (Session sessions, string title, string content, string from, list<string> receivers, Boolean ishtmlmail) {
    Message message = new MimeMessage (session);
      try {/** title **/logger.info ("This mail's title is {}", title);
      Message.setsubject (title);
      /** content **/logger.info ("This mail's content is {}", content);
      if (ishtmlmail) {//is an HTML mail message.setcontent (content, "text/html;charset=utf-8");
      else {//ordinary mail message.settext (content);
      /** the sender Address **/logger.info ("This mail's sender is {}", from);
      Address fromaddress = new internetaddress (from);
      Message.setfrom (fromaddress);
      /** recipient address **/address[] tos = new internetaddress[receivers.size ()];
        for (int i = 0; i < receivers.size (); i++) {String receiver = receivers.get (i);
        if (Validateutils.isemail (receiver)) {Tos[i] = new internetaddress (receiver);
     }}/** Send time **/ Message.setsentdate (New Date ());
    Message.setrecipients (Message.RecipientType.TO, TOS);
      catch (Messagingexception e) {logger.error (E.getmessage (), E);
    E.printstacktrace ();
  } return message; /** * Get Mailbox Domain name * * @param email address * @return/private string Getmailservicedomainname (string Emai
    L) {if (stringutils.isempty (email)) {return "";
      else {int firstindex = stringutils.indexof (email, "@");
 
      int secondindex = stringutils.lastindexof (email, ".");
    return stringutils.substring (email, firstindex + 1, secondindex);
  } public list<emailconfig> GetConfig () {return config;
  public void Setconfig (list<emailconfig> config) {this.config = config;
  public Boolean isdebug () {return isdebug;
  public void Setdebug (Boolean debug) {isdebug = Debug;
  public Boolean Isauth () {return isauth;
 } public void Setauth (Boolean auth) {   Isauth = auth;
  Public String Getauthtype () {return authtype;
  } public void Setauthtype (String authtype) {this.authtype = AuthType; }
}

The method is called as follows

public Boolean SendMail () throws Exception {
  list<string> receivers = new arraylist<string> ();
  Receivers.add ("sunhao0550@163.com");
  Receivers.add ("sunhao0550@sina.cn");
  Emailserver.getinstance (). Sendhtmlmail ("message_admin@163.com", "Here is password", "Test send HTML mail",
      "<span style= ' Color" : red;font-size:20pt ' > Test send HTML mail </span><a href= ' http://www.baidu.com ' target= ' _blank ' > link to Baidu </a > ", receivers);
  Return Emailserver.getinstance (). Sendtextmail ("message_admin@163.com", "Here is password", "Test send text message",
      " Test Send text message test send text message test send text message ", receivers);
}

PS: Considering extensions, how to extend the mail server configuration if these classes are sealed in a jar package.

If there is a bad place, welcome to Pat Bricks.

Related Article

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.