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