JavaMail Send mail (Hanshunping) __java

Source: Internet
Author: User
Tags auth
Main program:
Package Model;
public class Sendmailtosomeone {
public static void Main (String []args) {Sendmailtosomeone smts=new sendmailtosomeone (); Smts.send ("AA", "Hello", "Hanshu Nping@tsinghua.org.cn "," pinghan2005@sohu.com "," xxx "," smtp.sohu.com "); /** * Send email to designated mailbox * @param title   * @param mailbody Mail Content "A page, form OK" * @param SendTo sent to whom Hanshunping@tsinghua . org.cn * @param from which to send admin@sohu.com * @param passwd password 123456 * @param sendstmp SMTP smtp.sohu.com to send mail [smtp.163.c OM] [smtp.sina.com] */public void Send (String title,string mailbody,string sendto,string from,string passwd,string sends TMP) {//indicates that SMTP forwarding (Sohu) mysendmail themail = new Mysendmail (sendstmp);//Verify Identity Themail.setneedauth (TRUE);//Mail header if ( Themail.setsubject (title) = = False) return; Put the content you want to send into the mail body   if (themail.setbody (mailbody) = false) return; Where to send if (Themail.setto (sendTo) = = false) return; Who sent the IF (Themail.setfrom (from) = = false) return; if (Themail.addfileaffix ("e:\\butterfly.gif") = = false) return; if ()//the mail username and password will be placed on the Sohu website in the mail body   themAil.setnamepass ("pinghan2005", passwd); Send if (themail.sendout () = = false) return; } }


Mysendmail.java
Package Model;
Import java.util.*; Import javax.mail.*;
Import javax.mail.internet.*;
Import javax.activation.*;

public class Mysendmail {private mimemessage mimemsg;//mime Mail Object
Private session session; Mail Session object private Properties props; System Attribute Private Boolean Needauth = false; Does SMTP require authentication
Private String username = ""; SMTP authenticated user name and password private String password = "";
Private Multipart MP; Multipart objects, message content, headers, attachments, and so on are added to it before the MimeMessage object is generated



Public Mysendmail () {
Setsmtphost (getconfig.mailhost); If you do not specify a mail server, obtain Createmimemessage from the GetConfig class ();
}
Public Mysendmail (String SMTP) {setsmtphost (SMTP); Createmimemessage ();}

/** * @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 System Properties Object
Props.put ("Mail.smtp.host", hostName); Set SMTP Host}

/** * @return Boolean/public boolean createmimemessage () {try{System.out.println ("Ready to get the mail session object.") "); Session = Session.getdefaultinstance (props,null); There was an error getting the mail session object} catch (Exception e) {System.err.println. "+e); return false; }
System.out.println ("Prepares to create a 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; } }


/** * @param need boolean/public void Setneedauth (Boolean need) {System.out.println ("Set SMTP identity authentication: Mail.smtp.auth =" +nee D); if (props = = null) props = System.getproperties ();
if (need) {props.put ("Mail.smtp.auth", "true");} else{props.put ("Mail.smtp.auth", "false");}


/** * @param name String * @param pass String */public void Setnamepass (String name,string pass) {username = name; PASSW Ord = pass; }

/** * @param mailsubject String * @return Boolean/public boolean setsubject (string mailsubject) {System.out.println ("set The subject of the message. "); try{Mimemsg.setsubject (Mailsubject); return true;} catch (Exception e) {System.err.println ("Set the message subject error.") "); return false; } }


/** * @param mailbody string/public boolean setbody (string mailbody) {try{bodypart bp = new MimeBodyPart (); Bp.setcon Tent ("<meta http-equiv=content-type content=text/html; Charset=gb2312> "+mailbody", "text/html;charset=gb2312"); Mp.addbodypart (BP);
return true; An error occurred while setting the message body for catch (Exception e) {System.err.println. "+e); return false; } }

/** * @param name String * @param pass string/public boolean addfileaffix (String filename) {
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; An error occurred in catch (Exception e) {System.err.println ("Add Mail attachment: +filename+"). "+e); return false; } }


/** * @param name String * @param pass 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;}}

/** * @param name String * @param pass String */public Boolean setto (String to) {if (to = = null) return false;
try{mimemsg.setrecipients (Message.recipienttype.to,internetaddress.parse); return true;} catch (Exception e) { return false; }
}
/** * @param name String * @param pass String */public boolean setcopyto (String copyto) {if (CopyTo = = null) return false; try{mimemsg.setrecipients (Message.RecipientType.CC, (address[)) Internetaddress.parse (CopyTo); return true;} catch (Exception e) {return false;} }

/** * @param name String * @param pass String */public Boolean sendout () {try{mimemsg.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));

SYSTEM.OUT.PRINTLN ("The message was sent successfully.)             "); Transport.close ();
return true; The catch (Exception e) {System.err.println ("Mail send failed.")             "+e);     return false; }
}
}

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.