Java sends e-mail through SMTP

Source: Internet
Author: User
Tags html tags server website email account ssl connection

 PackageCom.sm.modules.oa.web;Importjavax.mail.Session;ImportJavax.mail.Transport;Importjavax.mail.internet.InternetAddress;ImportJavax.mail.internet.MimeMessage;Importjava.util.Date;Importjava.util.Properties; Public classSend {//Sender's mailbox and password (replaced by their mailbox and password)//PS: Some mailbox servers in order to increase the security of the mailbox itself password, to the SMTP client set up a separate password (some mailboxes called "Authorization Code"),//for a mailbox with a separate password, the password for the mailbox must be used for this individual password (authorization code).      Public StaticString myemailaccount = "[Email protected]";  Public StaticString Myemailpassword = "abcd2110401"; //the SMTP server address of the sender's mailbox must be accurate, different mail server addresses are different, general (only general, not absolute) format: smtp.xxx.com//NetEase 163 The SMTP server address of the mailbox is: smtp.163.com     Public StaticString myemailsmtphost = "smtp.163.com"; //recipient mailbox (replace with a valid mailbox that you know)     Public StaticString receivemailaccount = "[Email protected]";  Public Static voidMain (string[] args)throwsException {//1. Create parameter configuration to connect to the mail server's parameter configurationProperties props =NewProperties ();//parameter ConfigurationProps.setproperty ("Mail.transport.protocol", "SMTP");//protocol Used (JavaMail specification requirements)Props.setproperty ("Mail.smtp.host", myemailsmtphost);//SMTP server address for sender's mailboxProps.setproperty ("Mail.smtp.auth", "true");//Request Authentication Required//PS: Some mailbox servers require SSL security authentication for SMTP connections (for enhanced security, the mailbox supports SSL connections and can be turned on itself),//If you cannot connect to the mail server, look carefully at the log printed by the console, if there are errors such as "Connection failed, require SSL secure connection" ,//Open the SSL secure connection by opening the comment code between/* ... */.         /*the port of the SMTP 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 that needs to be the corresponding mailbox, the specific        Can see the corresponding mailbox service Help,//QQ mailbox SMTP (SLL) port 465 or 587, other mailboxes to see for themselves) Final String smtpport = "465";        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. Create a Session object based on the configuration to interact with the mail serverSession session =session.getdefaultinstance (props); Session.setdebug (true);//set to debug mode, you can view detailed send log//3. Create a messageMimeMessage message =Createmimemessage (Session, Myemailaccount, Receivemailaccount); //4. Get mail Transfer objects according to SessionTransport Transport =Session.gettransport (); //5. Use the email account and password to connect to the mail server, where the authenticated mailbox must be consistent with the sender mailbox in the message, otherwise the error//         //ps_01: The key to success or failure in this sentence, if the connection server fails, it will output the log of the corresponding failure reason in the console .//carefully review the reason for the failure, and some mailbox servers will return an error code or see a link to the error type, depending on the given error//type to the corresponding mail server on the help site to see the specific failure reason. //        //ps_02: The reason for the connection failure is usually the following, carefully examining the code://(1) The mailbox does not have SMTP service turned on; //(2) e-mail password error, for example, some mailboxes open a separate password; //(3) The mailbox server requires that SSL secure connection be used; //(4) The request is too frequent or other reasons, the mail server refused service; //(5) If the above points are OK, go to the mail server website to find help. //        //ps_03: Look at log carefully, read the log carefully, read the log, the cause of the error is described in log. Transport.connect (Myemailaccount, Myemailpassword); //6. Send the email to all of the receiving addresses, message.getallrecipients () Get all the recipients that were added when the message object was created, Cc, BCCtransport.sendmessage (Message, message.getallrecipients ()); //7. Close the connectionTransport.close (); }    /*** Create a simple message that contains only text * *@paramsession with server interaction *@paramsendMail Sender Email *@paramreceivemail Recipient Mailbox *@return     * @throwsException*/     Public StaticMimeMessage Createmimemessage (Session session, String SendMail, String receivemail)throwsException {//1. Create a messageMimeMessage message =NewMimeMessage (session); //2. From: the senderMessage.setfrom (NewInternetAddress (SendMail, "x Net", "UTF-8")); //3. To: Recipient (can add multiple recipients, CC, BCC)Message.setrecipient (MimeMessage.RecipientType.TO,NewInternetAddress (Receivemail, "xx user", "UTF-8")); //4. Subject: Mail SubjectMessage.setsubject ("Full 50 percent", "UTF-8"); //5. Content: Message body (HTML tags can be used)Message.setcontent ("xx user Hello, I love you, can I order a little praise of it ..." "," Text/html;charset=utf-8 "); //6. Set the sender timeMessage.setsentdate (NewDate ()); //7. Save Settingsmessage.savechanges (); returnmessage; }}

Java sends e-mail through SMTP

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.