In-depth discussion of the use of JavaMail API

zhaozj2021-02-16  78

In-depth discussion of the use of JavaMail API

In my previous article "Writing the JavaMail and JSP, writing simple email sending systems", introduces the method of using JavaMail and JSP. In fact, the Javamail API is a quite large system. Single Summer cannot introduce Javamail, so I want to explore the use of JavaMail in this article with you. Question 1. How do I send a simple letters? Answer: I will explain in detail how to send simple letters import java.util. *; Import javax.mail. *; Import javax.mail.internet. *; Import javax.activation. *; Import javax.Activation . *; public class sendsmemail {file: // msgtext is the body of the letter, there are two lines static string msgtext = "dear mr.fangzhou / ni'm a ready of your net!" File: // Read from the command line Three parameters, SMTPHOST, FROM, TO PUBLIC Static Void Main (String Args []) throws exception {if (args.length! = 3) {system.out.println ("USAGE: Java Sendsimplemail

");

Return;

}

String SMTPHOST = args [0]; //

SMTP server name

String from = args [1]; //

Sender address

String to = args [2]; //

Recipient address

//

Create a Properties object

Properties PROPS = New Properties ();

File: //

Create a mail server

Props.PUT ("mail.smtp.host", smtphost);

File: //

Get the default session

Session session = session.getDefaultInstance (Props, NULL);

//

Create a message and define the address of the sender's address and acceptor address

MimeMessage Message = New MimeMessage (session);

Message.SetFrom (New InternetAddress (from));

InternetAddress [] address = {new internetdress (to)};

Message.setRecipients (Message.RecipientType.to, Address);

Message.setSubject ("Hello, Fangzhou"); //

Set the subject

Message.setSentDate (new date ()); //

Set delivery time

Message.setText (msgtext); //

Set the text in the previously defined msgtext to the text of the text

File: //

send email

TRANSPORT.SEND (Message);

}

}

I have the question. If I want to add an attachment in the email?

This is also a very good problem. If you want to join annex, you should use mimebodypart to create a message, just add the above program to be modified, for simplicity, I just used a string as an attachment content. Explain how to add an attachment.

File: //

Msgtext is the body of the letter, two lines

Static string msgtext = "dear Mr.fangzhou / Ni'm a Reader of Your Net!" File: //

Msgattachment is a string as an attachment

Static string msgattachment = "this is an attachment string!"

..............

MIMEBODYPART MBP1 = new mimebodypart ();

Mbp1.settext (msgtext); file: //

Set the text in the previously defined msgtext to the text of the text

File: //

Create an accessory part

MIMEBODYPART MBP2 = new mimebodypart ();

File: //

Add accessories with setText (Text, Charset)

Mbp2.Settext (Msgattachment, "GB2312");

File: //

Create Multipart

Multipart mp = new mimemultipart ();

mp.addbodypart (MBP1);

mp.addbodypart (MBP2);

//

Add multipart to Message

Message.setContent (MP);

File: //

send email

TRANSPORT.SEND (Message);

}

Issue III, how do I get an email list from the mail server?

Answer: In fact, the method of achieving this problem is simple

1. JavaMail client starts a mail handling task by creating a default session (SESSION) object

Session session = session.getDefaultInstance (Props, Authenticator);

2. The client uses the GetStore method of the Session object to connect to the default to the Store provider. The getStore method returns a Store object subclass that supports the connection protocol defined in the user properties.

STORE store = session.getStore ();

Store.Connect ();

3. If the connection is successful, the client can list the available folders in the Store. Then we can get a specific Message object when you get or take it.

//

Obtain Inbox folder

Folder Inbox = Store.getFolder ("Inbox");

//

Open Inbox folder

Inbox.open (Folder.Read_write);

Message message [] = inbox.getMessage ();

For (int i = 0; filenumber = message.length; i

{

System.out.println ("Part i " Send: " Message [i] .GetFrom () [0] " / t " message [i] .getsubject ());

}

...

...

4. Finally, the client closes all open folders and close all store.

INBOX.CLOSE (); //

Close Inbox

Store.Close (); //

Close Store

Question 4: I want to delete some emails in the mailbox. What should I do?

On the mail server, if we want to delete a letter, simply call setflag () to set Flags.Flag.delete is true.

For example: message message = folder.getMessage (1);

Message.Setflag (Flags.Flag.deleted, true); file: // Setting flags.flag.delete is true. //

Check if the DELETED tag of this letter is set

IF (Flags.Flag.Deleted))

System.out.println ("This letter has been deleted, please return!");

Question 5: I want to know how many correspondence in my mailbox I have read how much correspondence, I haven't read, what should I do?

We know that the Folder object provides three methods, getMessageCount, GetNewMessageCount, and getunreadMessageCount. GetMessageCount method Displays how many letters in the mailbox, getnewMessageCount displays the number of new mail in the mailbox; getunReadMessageCount displays the number of seals that have been read in the mailbox. Using these three methods, we can easily see how many envelopes in the mailbox have we read, how many don't read it. See the program below:

Import javax.mail. *;

Import javax.mail.internet. *;

Public class checkmymailbox {

Public class void main ()

Throws exception {

Properties PROPS = New

//

Create a Properties object

Properties PROPS = New Properties ();

File: //

Get session

Session session = session.getDefaultInstance (Props, NULL);

File: //

Get a Store

Store Store = session.getStore ("POP3"); s

Store.Connect (POP3HOST, Username, Password);

File: //

Get Folder, open Inbox

Folder Inbox = Store.getFolder ("Inbox");

File: //

Open the mail clip with a read mode

Inbox.open (Folder.Read_only);

File: //

How much letter is made in the mailbox?

INT NUMBEROFTOAL = Inbox.getMessageCount ();

File: //

Get a letter that has not been read in the mailbox

Int numberofunread = inbox.getunreadMessageCount ();

System.out.println ("There is" Numberoft "in your mailbox," NumberOfunread "has not read");

File: //

Shut down connection

INBOX.CLOSE ();

Store.Close ();

Question 6: There is an attachment in my email, how do I open it?

Speaking of an attachment in the email, I have to say that the Multipart class, the Multipart class is a subclass of the Message class, providing additional implementation methods in the mail. A multi-segment message is a content type (Content-Type) is set to Multipart's Message object. The Multipart class is a container class that contains objects of the Bodypart type. The Bodypart object is an instance of a Part interface, which includes a new Multipart container object and includes a DataHandler object.

The figure below shows the structure of a Multipart message.

The figure below shows a typical Multipart mail nested

When there is an attachment in the message, the content of the message is Multipart instead of me. We need to obtain each part of Multipart and processed according to needs and content. Now let's take a look at how the program is implemented: import java.io. *;

Import java.util.properties;

Import javax.mail. *;

Import javax.mail.internet. *;

Public class getattachment {

Public static void main (string args [])

{

String host = args [0];

String username = args [1];

String Userpassword = args [2];

n = 3; //

For the sake of simplicity, I default third letter as an accessory mail.

Session session = session.getInstance (New Properties (), NULL

Store = session.getStore ("POP3");

Store.Connect (Host, UserName, UserPassword);

Folder folder = store.getfolder ("inbox");

Folder.open (Folder.Read_only);

Message message [] = folder.getMessage ();

Object content = message [n] .getContent ();

IF (Content InstanceOf Multipart)

{

HandleMultipart (MULTIPART) Content;

}

Else

{

Handlepart (Message [n]);

}

Folder.close ();

Store.Close ();

}

Public Static Void HandleMultipart (Multipart Multipart)

{

For (int i = 0, i

{

Handlepart (Multipart.getBodypart (i));

}

}

Public Static Void Handlepart (Part Part)

{

String disposit = part.getdisposition ();

String lastpe = part.getContentType ();

IF (Disposit == NULL) {//

If only text

System.out.println ("No:" Contype);

File: //

Check if it is an ordinary mail

IF ((Contype.Length ()> = 10) && (). Substring (0,10). Equals ("text / place"))) {

Part.writeto (System.out);

}

Else {

File: //

Mail that may be HTML format, but this article does not involve this content this is not considered.

System.out.println ("Other all the body:" contype);

Part.writeto (System.out);

}

}

Else IF (disposit.equals (part.attachment)) //

Otherwise, there is an attachment in the email.

{

System.out.println ("Attachment:" Part.getFileName () : Conty);

Storefile (Part.getFileName (), Part.getInputStream ());

}

Else {

System.out.println ("Others:" Disposit);

}

}

Public Static Void Storefile (String FileName, InputStream InputStream) / / Save File

{

File File = New File (filename);

FOR (int i = 0; file.exists (); i )

{

File = new file (filename i);

}

FileOutputStream FileOutputStream = New FileOutputStream (file);

BufferedoutputStream BufferedoutputStream = New BufferedOutputStream (FileoutputStream);

BufferedInputStream BufferedInputStream = New BufferedInputStream (BufferedInputStream);

Int n;

While ((n = bufferedInputStream.read ())! = - 1)

{

BufferedoutputStream.write (n);

}

BufferedoutputStream.flush ();

BufferedoutputStream.Close ();

BufferedInputStream.Close ();

}

}

This article uses some questions and corresponding answers, and everyone explores the use of JavaMail API, I hope this article will help everyone's learning and work.

转载请注明原文地址:https://www.9cbs.com/read-12312.html

New Post(0)