Javamail operational guidelines
Abstract: Javamail operational guidelines
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> Bromon original Please respect for copyright
<table Width="659" border="0"> <tr> <td width="268"> </ td> <td width="381"> what is relatively complete Javamail operational guidelines? I think the vast majority should include basic email operation will be able to meet the general application. In the Guide intends to include the following elements:
â— Send email: e-mail, including text, HTML mail, e-mail with attachments, SMTP Authentication â— receive email: pop3 Remote connections are charged by different MIME mail handling annex
I would like to have the above-mentioned functions, should be able to cope with the many applications of the email. Therefore, please allow me to compare this to be a pretentious name, in order to guarantee ratings,. I reiterate that the reasons for writing this post is not in line to see a more comprehensive, so remember that you read to me.
Below are examples of all the practical test, you can not say it written OO, plugable enough, but it can indeed reference. Ever since the birth of javamail, on the junk mail more convenient. In this paper, the less code and more, this is not my lazy, but a lot of things are involved pop3, and other agreements regulated If we do not understand these norms, from the things I really do not know how to explain to you; and if so, then I would not basically used to explain. So in practical principles has been omitted from the interest of their own agreement to standardize pointed out repeatedly.
</ Td> </ tr> </ table>
Less nonsense, first of all, need to configure the environment. Mail.jar package is needed and activation.jar. High version of the J2SDK EE own. Address place, a further search on java.sun.com, it is easy to find. Classpath put on KO.
First, send e-mail
Below the Longgan email Hello World, heat up:
/*************
Name: TextMailSender.java
Author: Bromon
Version: 1.0
Date: 2004-4-26
Note: Send email to bromon@163.com need to install the 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 ();
/ / Designated to be used as the SMTP server bromon2k
Prop.put ( "mail.smtp.host", "bromon2k");
Session mailSession = Session.getDefaultInstance (prop);
/ / Addresser
InternetAddress from = new InternetAddress ( "bromon @ bromon2k");
/ / Addressee
InternetAddress to = new InternetAddress ( "bromon@163.com");
MimeMessage msg = new MimeMessage (mailSession);
Msg.setFrom (from);
Msg.addRecipient (javax.mail.Message.RecipientType.TO, to);
/ / Date letters
Msg.setSentDate (new java.util.Date ());
/ / Title
Msg.setSubject ( "Hello");
/ / Mail Text
Msg.setText ( "hello, bromon");
Transport.send (msg);
) Catch (Exception e)
(
System.out.println (e);
)
)
)
The procedure is simple, but it is not running (inverted). Unless your machine has been installed an SMTP server, but you also called bromon2k machines. Write such a process can not be implemented in order to find not fight, but to give you the impression javamail there is a basic, I will not bother changed. Below is a demonstration of how the 163, sohu, such as email services to provide free e-mail to e-mail, basic operation and the same as above, but more than just a SMTP Authentication:
/ *
* 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); / / designated SMTP server
Props.put ( "mail.smtp.auth", "true ");// specified the need for SMTP Authentication
Try
(
Session mailSession = Session.getDefaultInstance (props);
MailSession.setDebug (true); / / console shows whether the debug information
Message message = new MimeMessage (mailSession);
Message.setFrom (new InternetAddress (from the sender ));//
Message.addRecipient (Message.RecipientType.TO, new InternetAddress (to the recipient ));//
Message.setSubject (subject); / / Subject
Message.setText (content); / / e-mail
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 ");// designated to use the mail server
Sm.setAccount ( "abc", "123 ");// designated ID and password
/ *
* @ Param String sender's address
* @ Param String Addressee
* @ Param String mail Title
* @ Param String mail Text
* /
Sm.send ( "abc@163.com", "bromon@163.com", "title", "Content");
)
)
This procedure does not seem to explain the need for it to SMTP addresses, account numbers, passwords, and configuration information inside wrote Properties, Java API inside many need to do this, for example, by adding further proceedings on the proxy server support.
The program above amend the server address, account number, password, can use, very simple.
How to send a HTML format Email? Also very simple, and the body of the e-mail to write HTML code, and then specify the ContentType mail on OK, only given the key code below:
……… ..
MimeMessage msg = new MimeMessage (mailSession);
Msg.setContent (content, "text / html");
Msg.setText ( " <body>
Below, you alright? </ Body> ");
……… ..
Below is the email sent with attachments, a little bit more complex, and in front of a number of different procedures, please carefully that, in the meantime, that IO knowledge. The same code is not in the list, only to write key parts, not everybody wants to get lazy?
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 ( "text messages");
MimeBodyPart fileBodyPart = new MimeBodyPart ();
FileDataSource fds = new FileDataSource ( "GIS.rar ");// sent to the Annex
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 MimeBodyPart posed by the two, this thing basically it is more difficult to explain if the relevant norms do not understand not very good explanation, and if so, I do not have to explain, this, this……… Alas.
Second, the collection of e-mail ↑ Back Tags: javamail
Under normal circumstances, we are close to an agreement to use pop3 mail, IMAP, just not now covered. Although the function of incoming mail, I spent a lot of time to understand the basic, but so easy to speak up, and a basic procedures can be included.
E-mail can be roughly three points: plain text e-mail, containing the text of other data mail messages containing 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 mail server access to all mail list
[] GetMail public Message (String host, String name, String password) throws Exception
(
Properties prop = new Properties ();
Prop.put ( "mail.pop3.host" host);
Session session = Session.getDefaultInstance (prop);
= Session.getStore store ( "pop3");
Store.connect (host, name and password);
Store.getDefaultFolder inbox = (). GetFolder ( "INBOX");
Inbox.open (Folder.READ_ONLY);
Message [] msg = inbox.getMessages ();
FetchProfile profile = new FetchProfile ();
Profile.add (FetchProfile.Item.ENVELOPE);
Inbox.fetch (msg, profile);
Return (msg);
)
/ / E-mail to deal with any need a method
Private void handle (Message msg) throws Exception
(
System.out.println ( "Subject:" + msg.getSubject ());
System.out.println ( "e-mail author:" + msg.getFrom () [0]. ToString ());
System.out.println ( "Date sent:" + msg.getSentDate ());
)
/ / Text e-mail
Public void handleText (Message msg) throws Exception
(
This.handle (msg);
System.out.println ( "e-mail:" + msg.getContent ());
)
/ / Multipart mail, including the preservation of the function of the annex
Public void handleMultipart (Message msg) throws Exception
(
String disposition;
BodyPart part;
Multipart mp = (Multipart) msg.getContent ();
Int mpCount = mp.getCount ();// Miltipart the quantity used in addition to several part, such as multiple attachments
For (int m = 0; m
This.handle (msg);
Part = mp.getBodyPart (m);
Part.getDisposition disposition = ();
If (disposition! = Null & disposition.equals (Part.ATTACHMENT)) / / determine whether there is any Annex
(
/ / This.saveAttach (part); / / This method is responsible for the preservation annex, in front of them because the annex could potentially be a virus, please clean up after Qudiao Box Notes
Else ()
System.out.println (part.getContent ());
)
)
)
Private void saveAttach (BodyPart part) throws Exception
(
String temp = part.getFileName ();// have not been dealt with Annex name
String s = temp.substring (11, temp.indexOf ("?=")- 1); / / to the header and footer
/ / File Name generally after base64 encoding, decoding Below are the
String fileName = this.base64Decoder (s);
System.out.println ( "Annex:" + 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 ();
)
/ / Decoding base64
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 the 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 receiver.getMail [] msg = (host, name and password);
For (int i = 0; i
If (msg [i]. IsMimeType ( "type text messages /*"))// judgement
(
Receiver.handleText (msg [i]);
Else ()
Receiver.handleMultipart (msg [i]);
)
System.out.println ("****************************");
)
Receiver.close ();
) Catch (Exception e)
(
System.out.println (e);
)
)
)
No java code reading habits brothers may feel a little trouble, there is a small problem, the annex to download the file name will be added after the "#" sign, I do not know this is javamail special handling or pop3 norms. File name changes through the process is very simple, there would not say. For email there are many other operations can take their own look javadoc, I do not explore the impact of all the fun. Properties in the proxy server configuration, the process can send and receive e-mail through a proxy, the general HTTP, socks 4, 5 support socks.
Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> </ tr> <tr>
Releated Java Articles
Comments
Leave a Reply






