Mail-sending program based on JavaMail packet----Kangkang

Source: Internet
Author: User
Tags abstract definition auth object interface variables prepare return variable
Program




The JavaMail API is an optional package (standard extension) for reading, writing, and sending electronic messages that can be used to establish standards-based e-mail clients that configure various Internet mail messages, including SMTP, POP, IMAP, and MIME, as well as related NNTP, S/MIME and other agreements. It is often necessary to develop javamail programs with the Sun's JavaBeans activation Framework (JAF). The operation of the JavaBeans activation framework is complex, which simply means that JavaMail's operation must depend on its support, such as JavaMail using JavaBeans activation framework To handle MIME-encoded message attachments. The JavaMail interface is contained in Javax.mail and its child packages, and the JavaBeans activation Framework interface is contained in the Javax.activation package, and the JAF specification is "Glasgow" JavaBeans For more details on JAF, please refer to the JAF guide:



Http://java.sun.com/beans/glasgow/jaf.html







The core JavaMail API consists of seven classes: Session, message, address, authenticator, transport, Store, and Folder, all from Javax.mail, the JavaMail API The top-level package. You can use these classes to accomplish a large number of common e-mail tasks, including sending messages, retrieving messages, deleting messages, authenticating, replying to messages, forwarding messages, managing attachments, processing messages based on HTML file formats, and searching or filtering mailing lists. For more information about JavaMail, refer to the JavaMail guide:



http://java.sun.com/products/javamail/







Similar to the JavaMail implementation of the SendMail program, there are many online. But the author found that most of them have a problem. My code is down there. Please make sure your machine has been installed JDK1.4 javamial1.3.2 and JAF before the mode is ready. If it is not installed, install the following steps:



1 Get the latest JDK from the www.java.sun.com website. Then set the Java environment variables.



If it is win95/98, add the following 3 line statements at the end of \autoexec.bat:



java_home=c:\j2sdk1.4.2



path=%java_home%\bin;%path%



Classpath=.; %java_home%\lib



Watch the Classpath first ".", this represents the current directory, many people HelloWorld not run up most of this is the reason.







If it is Win2000 or XP, use the mouse to right-click the "My Computer"-> Properties-> advanced-> Environment variables



System variable-> new-> variable name: Java_home variable Value: c:\j2sdk1.4.2



System variable-> edit-> variable name: Path at the front of the variable value plus:%java_home%\bin;



System variable-> new-> variable name: CLASSPATH variable value:.; %java_home%\lib\tools.jar;%java_home%\lib\dt.jar;



The one in front of the Classpath "." Is the same as the above meaning.



Please mode a HelloWorld to verify the installation is successful?



2 http://java.sun.com/products/javamail/Download the latest javamail.



Set Classpath=%classpath%;c:\download\javamail-1.3.2\mail.jar;.







3 http://java.sun.com/products/javabeans/glasgow/jaf.html Download JAF.



Set Classpath=%classpath%;c:\download\activation\activation.jar



4 OK. Finally, I can catch my breath first. Next, start the program section. Return the IF (Themail.setto ("########") = False) to the #号改为你自己的邮箱 in. Then return if (Themail.addfileaffix ("#######") = = False); In #写为本地的一个文件路径. can also be empty. For more people to learn, please do not modify the sendMail@163.com password: sendcode This mailbox only in the program test use!!



And then, in DOS,



Javac Sendmail.java



Java SendMail



Hehe Successful!!! My host DOS display



D:\>java SendMail



Set System Properties: Mail.smtp.host = smtp.163.com



Prepare to get mail Session Object!



Prepare to create MIME mail Object!



Set SMTP identity authentication: Mail.smtp.auth = True



Set the message theme!



Set Message size



Set up the addressee.



Set the sender!



Add Mail attachment: D:endmail.java



Program gets user name and password



Sending mail ....



Send mail Successful!



*************************************************************************



/**



* @author Kangkang



* http://corncc.ikdiy.com



* 2005.4.14



*/







Import java.util.*;



Import javax.mail.*;



Import javax.mail.internet.*;



Import Java.util.Date;



Import javax.activation.*;



Import java.io.*;











public class SendMail



{



21-30 lines to define the variables used in this program. Specifically, they are assigned to them in main.



Private MimeMessage mimemsg; MIME Mail Object







Private session session; Mail Session Object



Private Properties props; System Properties



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 SendMail (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); Setting up an SMTP host



}











/**



* @return Boolean



*/



public boolean createmimemessage ()



{



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 ("An error occurred while getting the mail session Object!") "+e);



return false;



}







SYSTEM.OUT.PRINTLN ("Prepare to create MIME mail Object!") ");



try{



mimemsg = new MimeMessage (session); To create a MIME mail object



MP = new Mimemultipart (); MP a multipart object



Multipart is a container which holds multiple body parts.



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 =" +need);



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)



{



SYSTEM.OUT.PRINTLN ("program gets username and password");



Username = name;



Password = pass;



}











/**



* @param mailsubject String



* @return Boolean



*/



public boolean setsubject (String mailsubject) {



SYSTEM.OUT.PRINTLN ("Set message subject!") ");



try{



Mimemsg.setsubject (Mailsubject);



return true;



}



catch (Exception e) {



SYSTEM.ERR.PRINTLN ("Set Message subject Error!") ");



return false;



}



}















/**



* @param mailbody String



*/



public boolean setbody (String mailbody)



{



Try



{



SYSTEM.OUT.PRINTLN ("Set message format");



BodyPart bp = new MimeBodyPart ();



Bp.setcontent ("<meta http-equiv=content-type content=text/html; Charset=gb2312> "



+mailbody, "text/html;charset=gb2312");



Mp.addbodypart (BP);







return true;



}



catch (Exception e)



{



SYSTEM.ERR.PRINTLN ("error when setting message body!") "+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;



}



catch (Exception e) {



System.err.println ("Add Mail attachment:" +filename+) error occurred! "+e);



return false;



}



}















/**



* @param name String



* @param pass String



*/



public boolean Setfrom (String from) {



System.out.println ("Set 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)



{



System.out.println ("Set up the addressee");



if (to = = null) return false;







Try



{



Mimemsg.setrecipients (To) (Message.recipienttype.to,internetaddress.parse);



return true;



}



catch (Exception e)



{return false;}







}







/**



* @param name String



* @param pass String



*/



public boolean Setcopyto (String CopyTo)



{



SYSTEM.OUT.PRINTLN ("Send attachment to");



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));



Transport.send (MIMEMSG);







SYSTEM.OUT.PRINTLN ("Send mail successful!") ");



Transport.close ();







return true;



}



catch (Exception e)



{



SYSTEM.ERR.PRINTLN ("Send mail failed!") "+e);



return false;



}



}











/**



* Just do it as this



*/



public static void Main (string[] args)



{







String mailbody = "Hello." This is a testing. ";







SendMail themail = new SendMail ("smtp.163.com");



Themail.setneedauth (TRUE);







if (Themail.setsubject ("dkjjf") = = false) return;



if (themail.setbody (mailbody) = = false) return;



if (Themail.setto ("########") = = false) return;



if (Themail.setfrom ("senfMail@163.com") = = false) return;



if (Themail.addfileaffix ("#######") = = false) return; Absolute path of attachment on Local machine



Themail.setnamepass ("SendMail", "Javacode"); User name and password



if (themail.sendout () = = false) return;



}



}



*************************************************************************



TIPS:



The front part of a program is just an abstract definition. The specific parameters are given in the main function.



B make good use of the process of SYSTEM.OUT.PRINTLN observation program execution.



C Reading javamaill\docs\javadocs\index.html








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.