JavaMail Operations Guide __java

Source: Internet
Author: User
Tags base64
Bromon Original Please respect the copyright

How to calculate the more complete JavaMail operation guide. I think it should include the vast majority of basic email operations that can handle general applications. The following are intended to be included in this guide:

Email: Include text messages, HTML messages, messages with attachments, SMTP authentication
Receive EMAIL:POP3 remote connections, receive different MIME messages, process attachments

I would like to have the above features introduced, should be able to deal with a lot of email related applications. So please allow me to give this article a more arrogant name, so as to ensure the ratings,. Or that sentence, the reason to write this post is not on the Internet to see more comprehensive, you read the words remember to tell me.

All of the following examples have been tested, you can say it is not oo, not plugable, but it can be referred to. Since the javamail, it is much more convenient to send junk mail. This article code more description less, this is not my lazy, but a lot of things are involved in POP3 and other protocols of the specification, if not understand these norms, by the things I really do not know how to explain to you, if you know, then I basically do not have to explain. So in line with the principle of practical omitted, by the interest of the words themselves to turn over the protocol specification.

Needless to say, you need to configure your environment first. The packages you need are Mail.jar and Activation.jar. A high version of the j2sdk EE self Band. Address, and then java.sun.com search, it is easy to find. Put it in the Classpath, Ko.

First, send the message

Here's an email Hello world, warm up:

 /*************
 name:textmailsender.java
 author:bromon
 version:1.0
 DATE:2004-4-26
 note: Send email to bromon@163.com, need to install SMTP server
 *************/
 package  org.bromon.mail;
 import javax.mail.*;
 import javax.mail.internet.*;
 import java.util.*;
 public class textmailsender
 {
 public static void main ( String args[])
 {
  try
  {
   properties prop= New properties ();
   //Specifies that the SMTP server you want to use is Bromon2k
   prop.put ("Mail.smtp.host", "bromon2k");
   session mailsession=session.getdefaultinstance (prop);

   //Sender Address
   internetaddress from=new internetaddress (" Bromon@bromon2k ");
   //recipient Address
   internetaddress to=new internetaddress (" Bromon@163.com ");
   
   mimemessage msg=new mimemessage (mailSession);
   msg.setfrom (from);
   msg.addrecipient (javax.mail.message.recipienttype.to,to);
   //Date
   msg.setsentdate (New java.util.date ());
   //title
   msg.setsubject ("Hello");
   //message body
   msg.settext ("Hello,bromon");
   transport.send (msg);
  }catch (exception e)
  {
   system.out.println (e);
  
 }
 } 


The program is simple, but it is not able to run (pour). Unless you have an SMTP server installed on your machine, and your machine is called bromon2k. Write such a paragraph can not execute the program is not to find a fight, but let you have a basic impression of javamail, I do not bother to change. The following shows how through 163, Sohu and other email service providers to send the free email address, the basic operation and above, just one more SMTP authentication only:

/*
* Created on 2004-4-26
*/
Package org.bromon.mail;
Import javax.mail.*;
Import java.util.*;
Import javax.mail.internet.*;

/**
* @author Bromon
*/
public class Senderwithsmtpver
{
String host= "";
String user= "";
String password= "";

public void Sethost (String host)
{
This.host=host;
}

public void Setaccount (String user,string password)
{
This.user=user;
This.password=password;
}

public void Send (String from,string to,string subject,string content)
{
Properties Props = new properties ();
Props.put ("Mail.smtp.host", host);//Specify SMTP server
Props.put ("Mail.smtp.auth", "true");//Specify whether SMTP authentication is required
Try
{
Session mailsession = session.getdefaultinstance (props);

Mailsession.setdebug (TRUE)//Whether debug information is displayed on the console

Message message=new mimemessage (mailsession);
Message.setfrom (new internetaddress from);//Sender
Message.addrecipient (Message.recipienttype.to,new internetaddress (to));//Recipient

Message.setsubject (subject);//Mail subject
Message.settext (content);//Message contents
Message.savechanges ();

Transport transport = Mailsession.gettransport ("SMTP");
Transport.connect (host, user, password);
Transport.sendmessage (Message, message.getallrecipients ());
Transport.close ();
}catch (Exception e)
{
System.out.println (e);
}

}

public static void Main (String args[])
{
Senderwithsmtpver sm=new senderwithsmtpver ();

Sm.sethost ("smtp.163.com");//Specify the mail server to use
Sm.setaccount ("abc", "123")//Specify account number and password

/*
* @param String Sender's address
* @param String recipient Address
* @param String message header
* @param String message body
*/
Sm.send ("abc@163.com", "bromon@163.com", "title", "Content");
}

}


This program does not seem to need to explain it, the SMTP address, account number, password and other configuration information written into the properties, Java inside a lot of APIs need to do so, such as the program to add to the proxy server support.

The above program changes the server address, account number, password can be used, very simple.

How to send an email in HTML format. Also very simple, then write the HTML code in the message body, then specify the contenttype of the message OK, the following only gives the key code:

...........
MimeMessage msg=new mimemessage (mailsession);
Msg.setcontent (Content, "text/html");
Msg.settext ("...........

Here is an email with an attachment, slightly more complex, and somewhat different from the previous program, please be careful and need a little IO knowledge. The same code is not listed, just write the key parts, everyone wants to be lazy not.

Import javax.mail.*;
Import javax.mail.internet.*;
Import javax.activation.*;
Import java.util.*;
..........
MimeMessage msg=new mimemessage (mailsession);
Msg.setsentdate (New Date ());
Msg.setsubject ("Hello");

MimeBodyPart textbodypart=new MimeBodyPart ();
Textbodypart.settext ("message body");

MimeBodyPart filebodypart=new MimeBodyPart ();
Filedatasource fds=new Filedatasource ("Gis.rar");/attachments to send
Filebodypart.setdatahandler (New DataHandler (FDS));
Filebodypart.setfilename (Fds.getname ());
Multipart container=new Mimemultipart ();
Container.addbodypart (Textbodypart);
Container.addbodypart (Filebodypart);
Msg.setcontent (container);
Transport.send (msg);
............


msg here is composed of two mimebodypart, this thing is basically difficult to explain, if you do not understand the relevant norms is not very good explanation, if you know, I do not have to explain, this ...  Alas. Second, the receipt of mail

Usually we use the POP3 protocol to collect emails, and IMAP is not involved now. The function of receiving mail although I spent a lot of time to understand the basic, but it is easy to speak, a program can be basically included.

Messages can be roughly divided into three types: plain text messages, text messages with other data, and messages that contain attachments.


CODE
/*
* Created on 2004-4-26
*/
Package org.bromon.mail;
Import javax.mail.*;
Import java.util.*;
Import java.io.*;

/**
* @author Bromon
*/
public class Receiver
{
Folder Inbox;
Store store;

 //connect to the mail server and get a list of all messages
 public message[] getmail (String host,string name, String password)  throws exception
 {
  Properties prop=new  Properties ();
  prop.put ("Mail.pop3.host", host);
  session session=session.getdefaultinstance (prop);
  store=session.getstore ("POP3");
  store.connect (Host,name,password);
  
  inbox=store.getdefaultfolder (). GetFolder ("Inbox");
  inbox.open (folder.read_only);
  
  message[] msg=inbox.getmessages ();
 &NBSP
  fetchprofile profile=new fetchprofile ();
  profile.add (FetchProfile.Item.ENVELOPE);
  inbox.fetch (Msg,profile);
  
  return (msg);
 .}

Ways to handle any kind of mail
private void handle (Message msg) throws Exception
{
System.out.println ("Mail Subject:" +msg.getsubject ());
System.out.println ("Mail Author:" +msg.getfrom () [0].tostring ());
SYSTEM.OUT.PRINTLN ("Send Date:" +msg.getsentdate ());
}

Working with text messages
public void Handletext (msg) throws Exception
{
This.handle (msg);
System.out.println ("Mail content:" +msg.getcontent ());
}

 //handles multipart messages, including the ability to save attachments
 public void handlemultipart (message msg)   Throws exception
 {
  string disposition;
  BodyPart part;
  
  multipart mp= (Multipart) msg.getcontent ();
  int mpcount=mp.getcount (); The number of//miltipart, used in addition to multiple parts, such as multiple attachments
  for (int m=0;m <mpcount;m++)
  {
   this.handle (msg);
&NBSP;&NBSP;&NBSP
   part=mp.getbodypart (m);
   disposition=part.getdisposition ();
   if (Disposition!=null && disposition.equals (Part.ATTACHMENT))//To determine whether there are attachments
   {
    //this.saveattach (part);//This method is responsible for saving the attachment, because the attachment may have a virus. Please clear the mailbox and then remove the annotation
   }else{
    system.out.println (Part.getcontent ());
&NBSP;&NBSP;&NBSP}
  }
 

 private void saveattach (Bodypart part)  throws exception
 {
   string temp=part.getfilename ()//Get the unprocessed attachment name
  string s=temp.substring (11, Temp.indexof ("? =")-1);//Go to Header and footer
  
  //filename is generally base64 encoded, following is decoding
   string filename=this.base64decoder (s);
  system.out.println ("There are attachments:" +filename);
  
  inputstream in=part.getinputstream ();
  fileoutputstream writer=new fileoutputstream (New file (fileName));
  byte[] content=new byte[255];
  int read=0;
  while (read=in.read (content)!=-1)
  {
   writer.write (content) ;
  }
  writer.close ();
  in.close ();
 }

Base64 decoding
private String Base64decoder (string s) throws Exception
{
Sun.misc.BASE64Decoder decoder = new Sun.misc.BASE64Decoder ();
Byte[] B=decoder.decodebuffer (s);

Return (new String (b));
}

Close connection
public void Close () throws Exception
{
if (inbox!=null)
{
Inbox.close (FALSE);
}

if (store!=null)
{
Store.close ();
}
}

public static void Main (String args[])
{
String host= "pop.163.com";
String name= "Bromon";
String password= "My password";

Receiver receiver=new Receiver ();

Try
{
Message[] Msg=receiver.getmail (Host,name,password);

for (int i=0;i<msg.length;i++)
{
if (Msg[i].ismimetype ("text/*"))//To determine the type of message
{
Receiver.handletext (Msg[i]);
}else{
Receiver.handlemultipart (Msg[i]);
}
System.out.println ("****************************");
}
Receiver.close ();
}catch (Exception e)
{
System.out.println (e);
}
}
}


A brother who is not accustomed to reading Java code may find it troublesome, and there is a small problem, the download of the attachment will be followed by a "#" symbol after the file name, do not know whether this is JavaMail special treatment or POP3 specifications. It's easy to change the file name by program, not to mention it. For email there are a lot of other operations, you can take a look at Javadoc, I will not affect the fun of everyone to explore. In the properties of the configuration Proxy server, you can let the program through the agent to send and receive mail, general HTTP, socks 4, socks 5 are supported.

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.