Java Send mail servlet (mail package is at the bottom)

Source: Internet
Author: User
Tags email account ssl connection

The JSP sends the message and processes it in the servlet. Mail package at the bottom, this article is reproduced from http://blog.csdn.net/xietansheng/article/details/51673073

Slightly modified on the basis of the above.

Package com.cn.restyle.servlet;
Import java.io.IOException;
Import Java.util.Date;
Import java.util.Properties;
Import javax.mail.NoSuchProviderException;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeMessage;
Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;  @WebServlet ("/sendmail") public class Sendmailservlet extends HttpServlet {private static final long Serialversionuid

    = 1L; Sender's mailbox and password/PS: Some mailbox servers in order to increase the security of the mailbox itself password, to the SMTP client set a separate password (some mailboxes called "Authorization Code"),//For the opening of a separate password mailbox, here's the mailbox password must make

        Use this standalone password (authorization code).
        public static String Myemailaccount = "Your 163 mailbox";

        public static String Myemailpassword = "Your mailbox password (authorization code)"; The server address of the sender's mailbox SMTP, the address of the server for the different mailboxes is generally different, the following is a 163 public static String Myemailsmtphost= "smtp.163.com";

        protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { String receiveremail = Request.getparameter ("Receiveremail");//Recipient String mailtitle = Request.getparameter (       "Mailtitle");    Message header String mailcontent = Request.getparameter ("mailcontent");
                Message body//1, configuration of parameter creation, parameter configuration for connecting to mail server properties props = new properties ();  Props.setproperty ("Mail.transport.protocol", "SMTP");  Use of the Protocol, JavaMail specification requirements Props.setproperty ("Mail.smtp.host", myemailsmtphost);           The address of the SMTP server for the sender's mailbox is Props.setproperty ("Mail.smtp.auth", "true"); Requests for authentication//PS: Some mailbox servers require SSL security authentication for SMTP connections (for increased security, the mailbox supports SSL connections, or it can be opened on its own),//
                If you cannot connect to the mail server, look carefully at the log of the console print, and if there are errors such as "Connection failed, require SSL secure connection",//Open the comment code between the/* ... *//SMThe port of the TP server (the port of the non-SSL connection is generally default to 25, can not be added, if the SSL connection is turned on,//The port of the SMTP server to the corresponding mailbox, you can view the corresponding mailbox clothing Service Help,//QQ mailbox SMTP (SLL) port is 465 or 587, other mailboxes to view the final String smtpport = "46
                5 ";
                Props.setproperty ("Mail.smtp.port", Smtpport);
                Props.setproperty ("Mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                Props.setproperty ("Mail.smtp.socketFactory.fallback", "false");
                Props.setproperty ("Mail.smtp.socketFactory.port", Smtpport);
                 *///2, based on configuration to create a session, for mail and server interaction sessions session=session.getinstance (props);       Session.setdebug (TRUE); Set to debug, you can view detailed log try {//3, create a mail object MimeMessage message=

                    Createmimemessage (Session,myemailaccount,receiveremail,mailcontent,mailtitle);
              4, according to the session to get the message transfer object       Transport transport =session.gettransport (); 5. Use the email account and password to connect to the mail server, where the authenticated mailbox must be the same as the sender's mailbox in message, otherwise the error////PS_01: The judgment of success or failure
                     Key in this sentence, if the connection to the server failed, will be in the console output the corresponding failure reason log,//check the cause of failure carefully, some mailbox server will return the error code or view the type of link, according to the error given
                     Type to the help site of the corresponding mail server to see the specific failure reason.
                     PS_02: The reason for the failure of the connection is usually the following, carefully check the code://(1) The mailbox does not open the SMTP service;
                     (2) Wrong mailbox password, for example, some mailboxes open a separate password;
                     (3) The mailbox server requires that SSL secure connection be used;
                     (4) Requests are too frequent or other reasons, the mail server refused service;
                     (5) If the above points are correct, to the mail Server Web site to find help.

                     PS_03: Look at the log carefully, look at the log, read log, the cause of the error in the log has been explained.

                     Transport.connect (Myemailaccount, Myemailpassword); 6, send the mail, sent to all the address of the Inbox, message.getallrecipients() gets all the recipients that were added when the mail object was created, CC, transport.sendmessage (message, message.getallrecipients ());

                7 Close connection transport.close ();
                catch (Nosuchproviderexception e) {e.printstacktrace ();
                catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();

    } response.sendredirect ("login.jsp"); public static MimeMessage Createmimemessage (Session session,string sendmail,string Receivemail, Stri ng mailcontent,string Mailtitle) throws exception{//1 Create an e-mail mimemessage message = new MimeMessage (ses

        sion);

        2 Sender Message.setfrom (new internetaddress (SendMail, "Xuheng", "Utf-8")); 3 recipients, can add multiple recipients, CC, MIDI message.setrecipient (MimeMessage.RecipientType.TO, New internetaddress (Receivemail, "Lisa
        "," Utf-8 ")); IncreaseRecipient Message.addrecipient (MimeMessage.RecipientType.TO, New internetaddress ("xuheng_z@126.com", "User_dd", "UTF-8")
        ); CC: CC (optional) message.setrecipient (MimeMessage.RecipientType.CC, New internetaddress ("1095201979@qq.com", "User_ee
        "," UTF-8 ")); BCC: MIDI (optional) message.setrecipient (MimeMessage.RecipientType.BCC, New internetaddress ("1432952955@qq.com", "User_

        FF "," UTF-8 "));

        4 Subject, mail subject message.setsubject (Mailtitle, "utf-8");

        5 Message body message.setcontent (mailcontent, "text/html;charset=utf-8");

        6 Set the time to send the message message.setsentdate (new Date ());
        7 Save Settings Message.savechanges ();

    return message; }

}

Note: Background development, the front of the basic blind spot, the style is ugly (laugh also suppressed, can not make a noise)

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >  

Mail package: Link: Https://pan.baidu.com/s/1kUFiviv Password: V7BG

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.