Spring provides an abstract layer for sending mail, which makes sending mail very simple.
BelowCodeThe mail. jar package is required. If the server requires authentication, add the following bold code:
Source File: Sendmail. Java:
Package mail;
Import org. springframework. Mail. javamail. javamailsenderimpl;
Import org. springframework. Mail. javamail. mimemessagehelper;
Import javax. Mail. Internet. mimemessage;
Import java. util. properties;
Import java. util. date;
/**
* @ Author chrischen
*/
Public class Sendmail {
// Email sender
Public static string sender (string subject, string MSG, string sendto, string frommail, string user, string PW, string fromname, string protocol, string host, string port ){
Try {
Final string username = user;
Final string pass = pw;
// Authentication required
Properties props = new properties ();
Props. Put ("mail. SMTP. Host", host );
Props. Put ("mail. SMTP. Auth", "true ");
Props. Put ("mail. Transport. Protocol", Protocol );
Props. Put ("mail. From", frommail );
// Create a sender
Javamailsenderimpl sender = new javamailsenderimpl ();
Sender. sethost (host );
Sender. setusername (username );
Sender. setpassword (PASS );
// Create a message
Mimemessage message = sender. createmimemessage ();
Message. addheader ("X-mailer", "Java Mailer ");
Mimemessagehelper helper = new mimemessagehelper (Message );
Helper. setto (sendto );
Helper. setfrom (frommail, fromname );
Helper. setsubject (subject );
Helper. settext (MSG );
Helper. setsentdate (new date ());
// Start sending
Sender. setjavamailproperties (props );
Sender. Send (Message );
} Catch (exception e ){
System. Out. println ("error:" + E );
Return" Failure ";
}
Return"Success ";
}
// Test
Public static void main (string ARGs []) throws exception
{
String subject = "test email"; // Title
String sendto = "test@my.com"; // recipient email
String frommail = "send@my.com"; // sender mail
String user = "send@my.com"; // sender user
String PW = "password"; // the sender's email password.
String fromname = "Chen"; // the sender's name.
String protocol = "SMTP"; // Protocol
String host = "smtp.my.com"; // sending host
String Port = "25"; // Port
String MSG = "send a simple email. "; // Send content
String ret = sender (subject, MSG, sendto, frommail, user, PW, fromname, protocol, host, Port );
System. Out. println ("email sending Result:" + RET );
}
}
UseMimemessagehelper can implement multipart email for adding attachments and embedded resources.