Java ways to send mail

Source: Internet
Author: User

1. Required jar Package

2. Concrete implementation Methods

1. Set up mailbox host, need authentication, mailbox agreement

Properties Pro=new properties ();

Pro.setproperty ("Mail.host", "smtp.qq.com");

Pro.setproperty ("Mail.smtp.auth", "true");

Pro.setproperty ("Mail.transport.protocol", "SMTP");

2. Setting the Validator

Authenticator auth=new Authenticator () {

@Override

Protected Passwordauthentication getpasswordauthentication () {

return new Passwordauthentication ("[Email protected]", "QZEAGWFNYXVGJGFF");

}

};

3. set up the socket layer to ensure the safety and reliability of the Protocol and Transportation

Mailsslsocketfactory sf=new mailsslsocketfactory ();

Sf.settrustallhosts (TRUE);

Pro.put ("Mail.smtp.ssl.enable", "true");

Pro.put ("Mail.smto.ssl.SocketFactory", SF);

4. Create a new message

Create session

Session session=session.getinstance (Pro,auth);

Session.setdebug (TRUE);

Create a message

MimeMessage Mime=new MimeMessage (session);

fill in the sender

Mime.setfrom (New InternetAddress ("[email protected]");

fill in the receiving person

Mime.setrecipients (recipienttype.to, "[email protected]");

Set Theme

Mime.setsubject ("Hello");

Set Body

Mime.setcontent ("Hello, Hi!") " ," Text/html;charset=utf-8 ");

Transport.send (MIME);

System.out.println (" sent successfully ");

How Java sends messages with attachments

Just comment out the settings body and change to:

send a message with an attachment

Mimemultipart list =new mimemultipart ();

Create body body Drop content

MimeBodyPart b1=new MimeBodyPart ();

B1.attachfile (New File ("c:\\users\\administrator\\desktop\\7.jpg"));

Chinese transcoding

B1.setfilename (Mimeutility.encodetext (" crayon Little New bullying . jpg"));

List.addbodypart (B1);

MimeBodyPart b2=new MimeBodyPart ();

B2.setcontent ("Hello, Hi!") " ," Text/html;charset=utf-8 ");

List.addbodypart (B2);

Mime.setcontent (list);

Transport.send (MIME);

System.out.println (" sent successfully ");

Java ways to send mail

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.