Using the JavaMail API to write mail-sending programs with attachments

Source: Internet
Author: User
Tags date mail
The program makes use of the JavaMail API provided by Sun Company to develop mail-sending programs easily. You may already be able to use it to send a simple text, but do you want to make your program send attachments like Outlook? After a brief introduction of JavaMail, this article explains in detail a complete messenger JavaBean and a very lightweight servlet.





(readers who do not have the JavaMail API loaded can download it and follow Readme.txt set classpath)


One, javamail some of the classes we need


1.Properties





JavaMail requires properties to create a Session object whose property value is the host that sends the message, such as:





Properties Props = new properties ();


props.put ("Mail.smtp.host", "smtp.xxxx.com")//can be replaced with your SMTP hostname, just as you set the SMTP host name in Outlook.





2.Session





all javamail based programs require at least one or all of the dialogue goals.





Session session = Session.getinstance (props, null);





3.MimeMessage




The
information object will truly reflect the message you send.





mimemessage msg = new MimeMessage (session);





4.Transport





Mail is sent by transport:





Transport.send (msg);





II, we create our own class that can send attachments


import java.util.*;


import java.io.*;


import javax.mail.*;


import javax.mail.internet.*;


import javax.activation.*;


public class Mail {


//define sender, recipient, subject, etc


String to= "";


String from= "";


String host= "";


String filename= "";


String subject= "";


//The collection of file names that are used to save send attachments


vector file = new vector ();


//Make a structure of the parameters such as the sender of a transmission


public Mail (String to,string from,string smtpserver,string subject) {


//Initialize sender, recipient, subject, etc


this.to=to;


This.from=from;


This.host=smtpserver;


This.subject=subject;


}


//This method is used to collect attachment names


public void Attachfile (String fname) {


file.addelement (fname);


}


//Start sending the letter method


public boolean startsend () {


//Create Properties Object


Properties props = System.getproperties ();


//Create a mail server


props.put ("Mail.smtp.host", host);


//Get the default Dialog object


session session=session.getdefaultinstance (props, null); try {


//Creates a message and initializes each element of the message


mimemessage msg = new MimeMessage (session);


Msg.setfrom (New InternetAddress (from));


internetaddress[] address={new internetaddress (To)};


msg.setrecipients (message.recipienttype.to,address);


Msg.setsubject (subject);


//Behind BodyPart will be added to the multipart created here


Multipart MP = new Mimemultipart ();


//using enumerators to easily traverse the set


enumeration efile=file.elements ();


//Check whether there are more objects in the sequence


while (efile.hasmoreelements ()) {


MimeBodyPart mbp=new MimeBodyPart ();


//Select each attachment name


filename=efile. Nextelement (). toString ();


//Get Data source


filedatasource fds=new filedatasource (filename);


//Get the attachment itself and into the BodyPart


Mbp.setdatahandler (New DataHandler (FDS));


//Get filename same to enter BodyPart


Mbp.setfilename (Fds.getname ());


Mp.addbodypart (MBP);


}


//Remove all elements from the collection


file.removeallelements ();


//multipart joined the letter


Msg.setcontent (MP);


//Set the sending date of the letter header


msg.setsentdate (New Date ());


//Send letter


transport.send (msg);


} catch (Messagingexception Mex) {


Mex.printstacktrace ();


Exception ex = null;


if ((Ex=mex.getnextexception ())!=null) {


Ex.printstacktrace ();


}


return false;


}


return true;


}


}





三、一个 a simple servlet


import javax.servlet.*;


import javax.servlet.http.*;


import java.io.*;


public class SendMail extends


HttpServlet implements singlethreadmodel{


public void init (ServletConfig Conf)


throws Servletexception {


Super.init (Conf);


}


public void DoPost (HttpServletRequest


Req, HttpServletResponse Res)


throws Servletexception, IOException {


try{


//Instantiate the class we just made, and pass the corresponding parameters according to its construction


Mail sendmail=newmail ("Zhang@263.net",


"chtwoy@21cn.com", "smtp.21cn.com", "Test");


sendmail.attachfile ("table.pdf");


Sendmail.startsend ();


}catch (Exception e) {


E.printstacktrace ();


}


}


public void Destroy () {


}


}




Summary of
Iv.


so far, you can add an attachment to a message, and you can have more than one. As such, separating the response from the logical phase is quite beneficial to the extension and maintenance of the code. If the beans and the servlet are not under the same package, don't forget to "import".








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.