Using JavaMail to send mail requires two packages of Mail.jar and Activtion.jar.
This class implements a more complete message forwarding function, including sending in HTML format, adding attachments and cc people. The following are the specific code:
Mail.java:
Package cn.cgw.util.mail;
Import java.util.Properties;
Import Javax.activation.DataHandler;
Import Javax.activation.FileDataSource;
Import javax.mail.Address;
Import Javax.mail.BodyPart;
Import Javax.mail.Message;
Import Javax.mail.Multipart;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeBodyPart;
Import Javax.mail.internet.MimeMessage;
Import Javax.mail.internet.MimeMultipart;
public class Mail {private mimemessage mimemsg;//mime Mail object private session sessions;//Mail Conversation object Private Properties props; System Attribute Private Boolean Needauth = false;
Whether SMTP requires authentication//smtp user name and password private String username;
private String password; Private Multipart MP;
Multipart objects, message content, headers, attachments, and so on are added to the MimeMessage object/** * constructor * @param SMTP mail server */Public Mail (String SMTP) {setsmtphost (SMTP);
Createmimemessage (); /** * Set Mail sending server * @param hostName string/public void Setsmtphost (string hostName
{System.out.println ("Set system properties: Mail.smtp.host =" +hostname); if (props = = null) props = System.getproperties (); Get the System attribute object Props.put ("Mail.smtp.host", hostName); Set SMTP Host}/** * Create MIME Mail Object * @return/public boolean Createmimeme Ssage () {try {System.out.println ("Ready to get mail Session Object!")
"); Session = Session.getdefaultinstance (props,null); Get mail Session object} catch (Exception e) {System.err.println: Error getting mail Session Object!
"+e);
return false; SYSTEM.OUT.PRINTLN ("Prepare to create MIME mail Object!")
"); try {mimemsg = new mimemessage (session);//create MIME mail Object MP = new MimemuLtipart ();
return true; catch (Exception e) {System.err.println ("Create MIME mail object failed!")
"+e);
return false; /** * Set SMTP to verify * @param need */public void Setneedauth (boolean n
Eed) {System.out.println ("Set SMTP identity authentication: Mail.smtp.auth =" +need);
if (props = = null) props = System.getproperties ();
if (need) {props.put ("Mail.smtp.auth", "true");
}else{props.put ("Mail.smtp.auth", "false"); /** * Set username and password * @param name * @param pass */public void Setnamepass (String name,string Pass)
{username = name;
Password = pass; /** * Set Mail subject * @param mailsubject * @return/public boolean setsubject (Strin G Mailsubject) {System.out.println ("set message theme!")
"); Try{Mimemsg.setsubject (mailsubject);
return true; catch (Exception e) {System.err.println ("Set the message subject Error!")
");
return false; }/** * Set message body * @param mailbody String/public boolean setbody (Strin
G mailbody) {try{bodypart bp = new MimeBodyPart ();
Bp.setcontent ("" "+mailbody," TEXT/HTML;CHARSET=GBK ");
Mp.addbodypart (BP);
return true; catch (Exception e) {System.err.println ("error when setting message body!")
"+e);
return false; }/** * Add attachment * @param filename string/public boolean Addfileaffix (string filen
AME) {System.out.println ("Add Mail attachment:" +filename);
try{bodypart bp = new MimeBodyPart (); Filedatasource fileds = new Filedatasource (filename);
Bp.setdatahandler (New DataHandler (fileds));
Bp.setfilename (Fileds.getname ());
Mp.addbodypart (BP);
return true; catch (Exception e) {System.err.println ("Add Mail attachment: +filename+" Error!)
"+e);
return false; }/** * Set sender * View more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/ java/* @param from String/public boolean Setfrom (string from) {System.out.println ("Set the sender!").
");
try{Mimemsg.setfrom (New InternetAddress (from));//Set sender return true;
catch (Exception e) {return false; /** * Set the recipient * @param to String/public boolean setto (string to) {I
F (to = = null) return false; try{mimemsg.setrecipients (Message.recipienTtype.to,internetaddress.parse (to));
return true;
catch (Exception e) {return false; }/** * Set cc person * @param copyto String */public boolean setcopyto (St
Ring CopyTo) {if (CopyTo = null) return false;
try{mimemsg.setrecipients (Message.RecipientType.CC, (address[)) Internetaddress.parse (CopyTo));
return true;
catch (Exception e) {return false;} /** * Send mail/public boolean sendout () {try{Mimem
Sg.setcontent (MP);
Mimemsg.savechanges ();
SYSTEM.OUT.PRINTLN ("Sending mail ...");
Session mailsession = Session.getinstance (props,null);
Transport transport = Mailsession.gettransport ("SMTP"); Transport.connect ((String) props.get ("Mail.smtp.host"), Username,password);
Transport.sendmessage (Mimemsg,mimemsg.getrecipients (Message.RecipientType.TO));
Transport.sendmessage (Mimemsg,mimemsg.getrecipients (Message.RecipientType.CC));
Transport.send (MIMEMSG); SYSTEM.OUT.PRINTLN ("Send mail successful!")
");
Transport.close ();
return true; catch (Exception e) {System.err.println ("Mail send failed!")
"+e);
return false; /** * Calls Sendout method completes mail send * @param SMTP * @param from * @param to * @
param subject * @param content * @param username * @param password * @return Boolean * * public static Boolean send (String smtp,string from,string to,string subject,string content,string username,string
Password) {Mail themail = new mail (SMTP); Themail.setneedauth (TRUE);
Need to verify if (!themail.setsubject (subject)) return false;
if (!themail.setbody (content)) return false;
if (!themail.setto) return false;
if (!themail.setfrom) return false;
Themail.setnamepass (Username,password);
if (!themail.sendout ()) return false;
return true; /** * Calls the Sendout method to complete the mail delivery, with CC * @param SMTP * @param from * @param to * @pa Ram CopyTo * @param subject * @param content * @param username * @param password * @return b Oolean */public static Boolean SENDANDCC (String smtp,string from,string to,string copyto,string subject,string
content,string username,string password) {Mail themail = new mail (SMTP); Themail.setneedauth (TRUE);
You need to verify if (!themail.setsubject (subject)) return false;
if (!themail.setbody (content)) return false; if (!themail.setto (to)) RetuRN false;
if (!themail.setcopyto (CopyTo)) return false;
if (!themail.setfrom) return false;
Themail.setnamepass (Username,password);
if (!themail.sendout ()) return false;
return true; /** * Calls the Sendout method to complete the mail send, with attachment * @param SMTP * @param from * @param to * @pa Ram Subject * @param content * @param username * @param password * @param filename attachment path * @r Eturn */public static Boolean send (String smtp,string from,string to,string subject,string content,string Usern
ame,string password,string filename) {Mail themail = new mail (SMTP); Themail.setneedauth (TRUE);
You need to verify if (!themail.setsubject (subject)) return false;
if (!themail.setbody (content)) return false;
if (!themail.addfileaffix (filename)) return false;
if (!themail.setto) return false; if (!themaIl.setfrom (from)] return false;
Themail.setnamepass (Username,password);
if (!themail.sendout ()) return false;
return true; /** * Calls Sendout method completes mail send, with attachments and CC * @param SMTP * @param from * @param to * @param copyto * @param subject * @param content * @param username * @param password * @param FileName * @return/public static Boolean SENDANDCC (String smtp,string from,string to,string copyto,str
ing subject,string content,string username,string password,string filename) {mail themail = new Mail (SMTP); Themail.setneedauth (TRUE);
You need to verify if (!themail.setsubject (subject)) return false;
if (!themail.setbody (content)) return false;
if (!themail.addfileaffix (filename)) return false;
if (!themail.setto) return false;
if (!themail.setcopyto (CopyTo)) return false; if (!themail.setfrom) return false;
Themail.setnamepass (Username,password);
if (!themail.sendout ()) return false;
return true; }
}
Test code:
public static void Main (string[] args) {
String SMTP = SMTP server;
String from = "Sender";
String to = "addressee";
String CopyTo = "cc person";
String subject = "message subject";
String content = "message content";
String username= "user name";
String password= "password";
String filename = "attachment path, such as: f:\\ notes <a>\\struts2</a> and Mvc.txt";
MAIL.SENDANDCC (SMTP, from, to, CopyTo, subject, content, username, password, filename);