Send a mailbox with no attachments:
Public void Test2 () throws exception{
//1: Claim server address
Properties P = new properties ();
p.setproperty ("Mail.host", "smtp.sohu.com");//Specify the server, take Sohu mailbox as an example
p.setproperty ("Mail.smtp.auth", "true");//Validation
Authenticator auth = new Authenticator () {
@Override
protected Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication ("xxxxxx", "password");
}
};
//2: Declare session
Session session = Session.getdefaultinstance (P,auth);
//Set to debug mode
Session.setdebug (true);
//3: Declaring information
Message msg = new MimeMessage (session);
Msg.setfrom (New internetaddress ("[email protected]");
msg.setrecipient (recipienttype.to,new internetaddress ("Email to be sent"));
Msg.setsubject ("title, who will");
msg.setcontent ("content, write Yourself", "text/html;charset=utf-8");
//Send
transport.send (msg);
}
To send a message containing an attachment:
Public void Test3 () throws exception{
//1: Claim server address
Properties P = new properties ();
p.setproperty ("Mail.host", "smtp.sohu.com");//Specify the server, take Sohu as an example
p.setproperty ("Mail.smtp.auth", "true");//Validation
Authenticator auth = new Authenticator () {
@Override
protected Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication ("xxxxxxx", "password");
}
};
//2: Declare session
Session session = Session.getdefaultinstance (P,auth);
//Set to debug mode
Session.setdebug (true);
//3: Declaring information
Message msg = new MimeMessage (session);
Msg.setfrom (New internetaddress ("[email protected]");
msg.setrecipient (recipienttype.to,new internetaddress ("Email to be sent"));
Msg.setsubject ("Everyone good 1111");
//Declaration multibody
Mimemultipart multi = new Mimemultipart ();
//Add an attachment
Javax.mail.internet.MimeBodyPart part1 = new Javax.mail.internet.MimeBodyPart ();
Part1.attachfile ("Address of File");
Part1.setfilename (Mimeutility.encodetext ("file name and suffix to send");
Multi.addbodypart (part1);
Javax.mail.internet.MimeBodyPart part2 = new Javax.mail.internet.MimeBodyPart ();
part2.setcontent ("Hello this is content <b>Hello</b>", "Text/html;charset=utf-8");
Multi.addbodypart (part2);
msg.setcontent (multi);
transport.send (msg);
}
Send mail with Java program