Several ways to send messages in Java __java

Source: Internet
Author: User
Tags auth

Mail was sent in a recent project, so I studied it. To sum it up.
to send a message you need to use the Java JavaMail, Javamailapi in the details of it in
(http://blog.csdn.net/imain/article/details/1453677) There is a very detailed introduction, I directly on the code.
1: Send mail using JavaMail

 1. Create a program and mail server session object Sessions Properties props = new properties ();
 Props.setproperty ("Mail.transport.protocol", "SMTP");
 Props.setproperty ("Mail.smtp.host", "smtp.163.com");
 Props.setproperty ("Mail.smtp.port", "25");
 Specifies that validation is true Props.setproperty ("Mail.smtp.auth", "true");
 Props.setproperty ("Mail.smtp.timeout", "1000"); Verify the account number and password, the password needs to be the third party authorization Code Authenticator AUTH = new Authenticator () {public passwordauthentication Getpasswordauthenticatio
            N ({return new passwordauthentication ("*******@163.com", "*******");
 }
        };

Session session = Session.getinstance (props, auth);
2. Create a message, which is equivalent to the mail content messages = new MimeMessage (session);
Set the sender Message.setfrom (new internetaddress ("*******@163.com"));
Set send mode with receiver Message.setrecipient (MimeMessage.RecipientType.TO, new internetaddress (email));
Set up the subject Message.setsubject ("Mail send Test");

Set content message.setcontent (emailmsg, "text/html;charset=utf-8"); 3. Create transport to send mail transport.send (message);

2: I'm using the spring framework, and spring encapsulates an Easy-to-use tool class Javamailsenderimpl for sending mail, so you can use Javamailsenderimpl to deliver mail.

public class Mailservice {private static final String HOST = "smtp.163.com";
    private static final Integer PORT = 25;
    private static final String USERNAME = "*******@163.com";
    private static final String PASSWORD = "*******";
    private static final String Emailform = "*******@163.com";
    private static Javamailsenderimpl MailSender = Createmailsender (); /** * Mail Transmitter * * @return configured Tools/private static Javamailsenderimpl Createmailsender () {J
        Avamailsenderimpl sender = new Javamailsenderimpl ();
        Sender.sethost (HOST);
        Sender.setport (PORT);
        Sender.setusername (USERNAME);
        Sender.setpassword (PASSWORD);
        Sender.setdefaultencoding ("Utf-8");
        Properties P = new properties ();
        P.setproperty ("Mail.smtp.timeout", "25000");
        P.setproperty ("Mail.smtp.auth", "false");
        Sender.setjavamailproperties (P);
    return sender;
  /** * Send mail * * @param to Recipient   * @param subject Theme * @param HTML send content * @throws messagingexception exception * @throws unsupportedencodingexce Ption Exception */public static void Sendhtmlmail (string to, string subject, string html) throws Messagingexception,uns
        upportedencodingexception {MimeMessage mimemessage = Mailsender.createmimemessage ();
        Set Utf-8 or GBK encoding, otherwise the message will have garbled mimemessagehelper messagehelper = new Mimemessagehelper (MimeMessage, True, "UTF-8");
        Messagehelper.setfrom (Emailform, "system name");
        Messagehelper.setto (to);
        Messagehelper.setsubject (subject);
        Messagehelper.settext (HTML, true);
    Mailsender.send (MimeMessage); }
}

Of course this is the hard coded way. It can also be written in a resource file.

Resource file

Mailconfig.properties
#服务器
mailhost=smtp.163.com
#端口号
mailport=25
#邮箱账号
mailusername=* @163.com
#邮箱授权码
mailpassword=*******
#时间延迟
mailtimeout=25000
#发送人
mailfrom=*** @163.com

Get the contents of a resource file

public class Mailconfig {private static final String Properties_default = "Mailconfig.properties";
    public static String host;
    public static Integer port;
    public static String UserName;
    public static String PassWord;
    public static String Emailform;
    public static String timeout;
    public static String personal;
    public static properties properties;
    static{init ();
        }/** * Initialize/private static void Init () {properties = new properties ();
            try{InputStream InputStream = MailConfig.class.getClassLoader (). getResourceAsStream (Properties_default);
            Properties.load (InputStream);
            Inputstream.close ();
            Host = Properties.getproperty ("Mailhost");
            Port = Integer.parseint (Properties.getproperty ("Mailport"));
            UserName = Properties.getproperty ("Mailusername");
            PassWord = Properties.getproperty ("MailPassword"); Emailform = PropErties.getproperty ("Mailfrom");
            Timeout = Properties.getproperty ("Mailtimeout");
        Personal = "Mexican descent";
        catch (IOException e) {e.printstacktrace (); }
    }
}

Send mail

public class Mailutil {private static final String HOST = mailconfig.host;
    private static final Integer PORT = Mailconfig.port;
    private static final String USERNAME = mailconfig.username;
    private static final String PASSWORD = Mailconfig.password;
    private static final String emailform = Mailconfig.emailform;
    Private static final String timeout = mailconfig.timeout;
    Private static final String personal = mailconfig.personal;
    private static Javamailsenderimpl MailSender = Createmailsender (); /** * Mail Transmitter * * @return configured Tools/private static Javamailsenderimpl Createmailsender () {J
        Avamailsenderimpl sender = new Javamailsenderimpl ();
        Sender.sethost (HOST);
        Sender.setport (PORT);
        Sender.setusername (USERNAME);
        Sender.setpassword (PASSWORD);
        Sender.setdefaultencoding ("Utf-8");
        Properties P = new properties ();
        P.setproperty ("Mail.smtp.timeout", timeout); P.setproperTy ("Mail.smtp.auth", "false");
        Sender.setjavamailproperties (P);
    return sender; /** * Send mail * * @param to Recipient * @param subject Theme * @param HTML send content * @throws Messagi Ngexception Exception * @throws unsupportedencodingexception exception */public static void SendMail (string to, string su Bject, String html) throws Messagingexception,unsupportedencodingexception {mimemessage mimemessage = MailSender.
        Createmimemessage ();
        Set Utf-8 or GBK encoding, otherwise the message will have garbled mimemessagehelper messagehelper = new Mimemessagehelper (MimeMessage, True, "UTF-8");
        Messagehelper.setfrom (Emailform, personal);
        Messagehelper.setto (to);
        Messagehelper.setsubject (subject);
        Messagehelper.settext (HTML, true);
    Mailsender.send (MimeMessage);
 }
}

The source code has been uploaded and can be downloaded
Https://github.com/wolf521/demo/tree/master/src/main/java/com/example/demo/mail

Jar Package Download
http://download.csdn.net/download/qq_32371887/10123280

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.