Java Mail implementation of third-party mail delivery function

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

1 Creating a class for sending messages

1  PackageCom.latiny.service;2 3 Importjava.io.IOException;4 ImportJava.io.InputStream;5 Importjava.util.Date;6 Importjava.util.Properties;7 Importjavax.mail.Session;8 ImportJavax.mail.Transport;9 Importjavax.mail.internet.InternetAddress;Ten ImportJavax.mail.internet.MimeMessage; One  A  Public classSendMail { -      -      /* the 1 sender's mailbox and password - 2 Some mailbox servers in order to increase the security of the mailbox itself password, the SMTP client set a separate password (some mailboxes are called "Authorization Code"), - 3 for a mailbox with a separate password, the password must be used for this individual password (authorization code).  -      */ +     PrivateString SendEmail; -     PrivateString password; +     A     //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 at     PrivateString host; -      -     //Recipient Mailbox -     PrivateString Receiveemail; -      -     //send a topic, send content in     PrivateString subject; -     PrivateString content; to      +     //reading configuration Files -     PrivateProperties pp; the InputStream instream; *      $     //assigning values to member variables from the system's configuration filePanax Notoginseng     Private voidinitvariable () -     { thePP =NewProperties (); +Instream = SendMail.class. getClassLoader (). getResourceAsStream ("Com/latiny/service/emailconfig.properties"); A         Try  the         { + pp.load (instream); -SendEmail = Pp.getproperty ("SendEmail"); $Password = pp.getproperty ("Password"); $Host = Pp.getproperty ("host"); -              -}Catch(IOException e) { the             //TODO auto-generated Catch block - e.printstacktrace ();Wuyi         } the     } -      Wu      PublicSendMail (String receiveemail, string subject, string content) -     { About          This. Subject =subject; $          This. Receiveemail =Receiveemail; -          This. Content =content; - initvariable (); - sendout (); A     } +      the     PrivateMimeMessage CreateMessage (Session session, string subject, string content)throwsException -     { $         //Create a Mail object theMimeMessage message =NewMimeMessage (session); the          the         //Set Sender theMessage.setfrom (NewInternetAddress (SendEmail, "Order succeeded", "UTF-8")); -          in         //Recipients (can add multiple recipients, CC, BCC) theMessage.setrecipient (MimeMessage.RecipientType.TO,NewInternetAddress (Receiveemail, "Latiny user", "UTF-8")); the          About         //Message Subject theMessage.setsubject (Subject, "UTF-8"); the          the         //Content: Message body (HTML tags can be used) +Message.setcontent (Content, "Text/html;charset=utf-8"); -          the         //Sending TimeBayiMessage.setsentdate (NewDate ()); the  the         //Save Settings - message.savechanges (); -          the         returnmessage; the     } the  the     Private voidsendout () -     { the          the         Try  the         {94             //Create a parameter configuration for connecting to the mail server's parameter configuration theProperties props =NewProperties ();//parameter Configuration theProps.setproperty ("Mail.transport.protocol", "SMTP");//protocol Used (JavaMail specification requirements) theProps.setproperty ("Mail.smtp.host", host);//SMTP server address for sender's mailbox98Props.setproperty ("Mail.smtp.auth", "true");//Request Authentication Required About              -             //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),101             //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" ,102             //Open the SSL secure connection by opening the comment code between/* ... */. 103             //the port of the SMTP server (the port of the non-SSL connection generally defaults to 25, can not be added, if the SSL connection is turned on, you need to change the port of the SMTP server that corresponds to the mailbox, you can see the Help for the corresponding mailbox service .104             //QQ Mailbox SMTP (SLL) port is 465 or 587, other mailboxes to see for themselves) the             106             /* 107 final String smtpport = "465";108 props.setproperty ("Mail.smtp.port", smtpport);109 props.setproperty ("Mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); the props.setproperty ("Mail.smtp.socketFactory.fallback", "false");111 props.setproperty ("Mail.smtp.socketFactory.port", smtpport); the             */113              the             //Create session objects based on configuration to communicate with mail servers theSession session =session.getinstance (props); theSession.setdebug (true);117MimeMessage message = This. CreateMessage (Session, This. Subject, This. content);118             119              //Get message Transfer objects based on Session -Transport Transport =Session.gettransport ();121             122             //Use your email account and password to connect to the mail server, where the authenticated mailbox must match the sender's mailbox in the message, otherwise the error123             // 124             //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 . the             //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 error126             //type to the corresponding mail server on the help site to see the specific failure reason. 127             // -             //ps_02: The reason for the connection failure is usually the following, carefully examining the code:129             //(1) The mailbox does not have SMTP service turned on; the             //(2) e-mail password error, for example, some mailboxes open a separate password;131             //(3) The mailbox server requires that SSL secure connection be used; the             //(4) The request is too frequent or other reasons, the mail server refused service;133             //(5) If the above points are OK, go to the mail server website to find help. 134             //135             //ps_03: Look at log carefully, read the log carefully, read the log, the cause of the error is described in log. 136 Transport.connect (Sendemail,password);137             138             //send a message to all of the receiving addresses, message.getallrecipients () gets all the recipients that were added when the message object was created, Cc, BCC .139 transport.sendmessage (Message, message.getallrecipients ()); $             141             //Close Connection142 transport.close ();143             144}Catch(Exception e) {145             //TODO auto-generated Catch block146 e.printstacktrace ();147         }148     }149      Max}

Configuration file Emailconfig.properties:

SendEmail = [email protected]==smtp.163.com

  

Java Mail enables third-party mail delivery

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.