Java Send mail (plain text and with attachments)

Source: Internet
Author: User

public class Testmail {

Plain text
@Test
public void Fun () throws addressexception,messagingexception{
Properties Prop=new properties ();
Prop.setproperty ("Mail.host", "smtp.163.com");
Prop.setproperty ("Mail.smtp.auth", "true");
Authenticator auth=new Authenticator () {
Protected Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication ("Sender's Mailbox", "Sender's password");
}
};
Session session=session.getinstance (Prop,auth);
MimeMessage Msg=new MimeMessage (session);
Msg.setfrom (New InternetAddress ("sender's Mailbox"));
Msg.setrecipients (Recipienttype.to, "recipient's mailbox");
Msg.setsubject ("La la!!!"); /title
Msg.setcontent ("La La la! "," Text/html;charset=utf-8 "); Content
Transport.send (msg);
}
With accessories.
@Test
public void Fun2 () throws addressexception,messagingexception,ioexception{
Properties Prop=new properties ();
Prop.setproperty ("Mail.host", "smtp.163.com");
Prop.setproperty ("Mail.smtp.auth", "true");
Authenticator auth=new Authenticator () {
Protected Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication ("Sender's Mailbox", "Sender's password");
}
};
Session session = Session.getinstance (prop, auth);
MimeMessage msg = new MimeMessage (session);
Msg.setfrom (New InternetAddress ("sender's Mailbox"));
Msg.setrecipients (Recipienttype.to, "recipient's mailbox");
Msg.setsubject ("Test Mail"); Title
Mimemultipart list = new Mimemultipart ();
MimeBodyPart part1 = new MimeBodyPart ();
Part1.setcontent ("La La la! "," Text/html;charset=utf-8 "); Content
List.addbodypart (part1);
MimeBodyPart part2 = new MimeBodyPart ();
Part2.attachfile ("D:\\title_en.png"); Attachment
Part2.setfilename (Mimeutility.encodetext ("title_en.png"));
List.addbodypart (part2);
Msg.setcontent (list);
Transport.send (msg);
}
}

Java Send mail (plain text and with attachments)

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.