Send emails and attachments to javamail (source code)

Source: Internet
Author: User
Tags email account

Javamail is Sun's application interface for email processing. It provides some of the most common implementation methods for mail transfer protocols and provides easy methods to call them. Javamail is an application interface released by Sun, so it is not included by JDK yet. Therefore, you need to download the javamail package from Sun's official website. In addition, sun's JAF (JavaBeans activation framework) is also required. Otherwise, javamail cannot run.

The core javamail API consists of seven classes: Session, message, address, authenticator, transport, store, and folder. They all come from javax. Mail, that is, javamail API top-level packages. You can use these classes to complete a large number of common email tasks, this includes sending, retrieving, deleting, authenticating, replying, forwarding, managing attachments, processing HTML file-based messages, and searching or filtering email lists. For more information about javamail, see the javamail guide.

 

Basic knowledge of javamail

Using javamail is a required component for sending emails.

The javamail organization makes it easy to process emails. The following lists the classes we need:

1. Properties

Javamail needs properties to create a session object. It will look for the string "mail. SMTP. Host". The attribute value is the host that sent the mail, for example:

Properties props = new properties ();

Props. Put ("mail. SMTP. Host", "smtp.sina.com"); // you can replace it with your SMTP host name.

Props. Put ("mail. SMTP. Auth", "true"); // identity verification. Currently, this item is required for free email servers.

2. Session

This session class represents a mail session in javamail. Each javamail-based application has at least one session (which can have any number of sessions ). In this example, the session object needs to know the SMTP server used to process the mail. To do this, you can create a Session Object using properties in the following example.

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

3. Transport

An email can be sent or received. Javamail uses two different classes to complete these two functions: Transport and store. Transport is used to send information, while store is used to receive mail. For this tutorial, we only need to use the transport object. For the usage of store, see Sun's javamail document.

Usage: transport Transport = session. gettransport ("SMTP ");

Use the gettransport method of the javamail Session object to initialize the transport. The passed string declares the protocol used by the object, such as "SMTP ". This saves us a lot of time. Because javamail already has many built-in protocol implementation methods.

Note: javamail does not absolutely support every protocol. Currently, it supports IMAP, SMTP, and POP3.

4. Message

The message object stores the actually sent email information. The message object is created as a mimemessage object and needs to know which javamail session should be selected.

Message message = new mimemessage (session );

 

Email garbled:

The email subject in javamail needs to be base64 encoded. The format is like: =? GBK? B? Xpq1xmpcwuvs0b6t1tjww6osx + u + OB/stcfcvkossqlq3rjew9zc66oh? =

Therefore, use message directly. setsubject ("Chinese topic"), or message. setsubject ("Chinese topic ". getbytes ("ISO-8859-1"), "GBK") are the same as garbled characters. Before setting a subject, encode the topic string in base64 format and add an encoding header. The sample code is as follows:

Sun. Misc. base64encoder ENC = new sun. Misc. base64encoder ();

MSG. setsubject ("=? GBK? B? "+ Enc. encode (subject. getbytes () + "? = ");

 

Source code of email sending:

 

Sendmail. Java

Package com. LZW. mail;

 

Import java. util. arrays;

Import java. util. date;

Import java. util. properties;

 

Import javax. Activation. datahandler;

Import javax. Activation. datasource;

Import javax. Activation. filedatasource;

Import javax. Mail. address;

Import javax. Mail. authenticator;

Import javax. Mail. bodypart;

Import javax. Mail. message;

Import javax. Mail. messagingexception;

Import javax. Mail. multipart;

Import javax. Mail. nosuchproviderexception;

Import javax. Mail. passwordauthentication;

Import javax. Mail. Session;

Import javax. Mail. Transport;

Import javax. Mail. Internet. addressexception;

Import javax. Mail. Internet. internetaddress;

Import javax. Mail. Internet. mimebodypart;

Import javax. Mail. Internet. mimemessage;

Import javax. Mail. Internet. mimemultipart;

 

Import com. LZW. Io. out;

/**

* Email sending program

* @ Author Li Zhao Wei create: 2007-12-19

*/

Public class Sendmail {

Private session; // session

Private transport; // send an email

 

Private user; // email-related account information

Private mailaddress; // recipient address

Private mailbody; // mail content

Private final string mail_smtp_host = "mail. SMTP. Host ";

Private final string mail_smtp_auth = "mail. SMTP. Auth ";

 

Public Sendmail (User user ){

This. User = user;

Init ();

}

 

/**

* Initialize <code> session, transport </code>

*/

Private void Init (){

Authenticator auth = new authenticator (){

Protected passwordauthentication getpasswordauthentication (){

Return new passwordauthentication (user. GetUserName (), user

. GetPassword ());

}

};

 

Properties props = new properties ();

// Set the attributes of the email sending server (Netease's SMTP server is used here)

Props. Put (mail_smtp_host, user. gethost ());

// Authorization is required, that is, verification of the account name and password is required to pass the verification (this is required)

Props. Put (mail_smtp_auth, "true ");

// Construct a session with the set props object

Session = session. getdefainstance instance (props, auth );

Try {

// Send an email

Transport = session. gettransport ("SMTP ");

// The email address of the connection Server

Transport. Connect (user. gethost (), user. GetUserName (), user

. GetPassword ());

} Catch (nosuchproviderexception e ){

E. printstacktrace ();

} Catch (messagingexception e ){

E. printstacktrace ();

}

Out. PLN ("and" + User. gethost () + "successfully established session ");

}

 

/**

* Set the recipient address

*

* @ Param mailaddress

*/

Public void setaddress (mailaddress ){

This. mailaddress = mailaddress;

}

 

/**

* Set email content

*

* @ Param mailbody

*/

Public void setmailbody (mailbody ){

This. mailbody = mailbody;

}

 

/**

* Construct the mail content

*

* @ Return

* @ Throws addressexception

* @ Throws messagingexception

*/

Private Message createmessage () throws addressexception, messagingexception {

// Define the message object using session as the parameter

Mimemessage message = new mimemessage (session );

// Load the sender address

Message. setfrom (New internetaddress (user. getfrom ()));

Message. setsentdate (new date ());

// Load the recipient address

Message. addrecipients (message. recipienttype. To, getaddress (mailaddress

. Getto ()));

If (mailaddress. ishascc ())

Message. addrecipients (message. recipienttype. CC,

Getaddress (mailaddress. getcc ()));

 

// Load the title

Message. setsubject (mailbody. getsubject ());

 

If (mailbody. iscontentflag () | mailbody. isaffixflag ()){

// Add each part of the email to the multipart object, including text content and attachments.

Multipart = new mimemultipart ();

 

If (mailbody. iscontentflag ()){

// Set the text content of the email

Mimebodypart contentpart = new mimebodypart ();

If (mailbody. ismimecontent ())

Contentpart. setcontent (mailbody. getcontent (),

"Text/html; charset = GBK ");

Else

Contentpart. settext (mailbody. getcontent ());

Multipart. addbodypart (contentpart );

}

 

If (mailbody. isaffixflag ()){

// Add an attachment

Bodypart affixbody = new mimebodypart ();

Datasource source = new filedatasource (mailbody. getaffix ());

// Add the attachment content

Affixbody. setdatahandler (New datahandler (source ));

// It is very important to add the title of the attachment. You can use the base64 encoding below to ensure your

// The title name of the Chinese attachment will not become garbled during sending

Sun. Misc. base64encoder ENC = new sun. Misc. base64encoder ();

String filename = "=? GBK? B? "

+ Enc. encode (mailbody. getaffixname (). getbytes () + "? = ";

Affixbody. setfilename (filename );

Multipart. addbodypart (affixbody );

}

 

// Put the multipart object in the message

Message. setcontent (multipart );

}

// Save the email

Message. savechanges ();

Return message;

}

 

/**

* Send an email, including the body of the email and (one attachment)

*

* @ Param debug

* Debugging settings

*/

Public void send (Boolean Debug ){

// With this statement, the process information can be displayed on the console during email sending for debugging.

// Use (you can see the mail sending process on the console)

Session. setdebug (Debug );

Try {

Message message = createmessage ();

Transport. sendmessage (message, message. getallrecipients ());

} Catch (addressexception e ){

E. printstacktrace ();

} Catch (messagingexception e ){

E. printstacktrace ();

}

 

Out. PLN ("/n ----------------------------------------------------------");

Out. PLN ("-the email is sent successfully! ");

Out. PLN ("-to:" + arrays. tostring (mailaddress. getto ()));

If (mailaddress. ishascc ())

Out. PLN ("-CC:" + arrays. tostring (mailaddress. getcc ()));

Out. PLN ("----------------------------------------------------------/N ");

}

 

/**

* Close Resources

*

* @ Throws messagingexception

*/

Public void close () throws messagingexception {

If (null! = Transport)

Transport. Close ();

}

 

Public Address [] getaddress (string [] address) throws addressexception {

Address [] addrs = new internetaddress [address. Length];

For (INT I = 0; I <address. length; I ++)

Addrs [I] = new internetaddress (Address [I]);

Return addrs;

}

 

/**

* Test

*/

Public static void main (string [] ARGs ){

String host = "smtp.sina.com ";

String username = "";

String Password = "";

// String from = "";

String to = "";

// String cc = NULL;

String subject = "test ";

String content = "<a href = http://www.baidu.com> Baidu </a> ";

Boolean mimecontent = true;

String affix = "D:/temp/temp.txt ";

String affixname = "temp.txt ";

Boolean DEBUG = false;

// String userfile = "user. properties ";

// String addressfile = "mailaddress. properties ";

 

Sendmail mail = NULL;

Try {

Try {

User user = new user (host, username, password );

Mailaddress = new mailaddress ();

 

// User = new user (userfile );

// Mailaddress = new mailaddress (sendmail. Class

//. Getresourceasstream (addressfile ));

 

Mailbody = new mailbody (subject, content, mimecontent,

Affix, affixname );

Mail = new Sendmail (User );

// For (INT I = 0; I <5; I ++ ){

// Set the sender address, recipient address, and mail title

Mail. setaddress (mailaddress );

 

// Set the location and title of the attachment to be sent

Mail. setmailbody (mailbody );

// Set the SMTP server and email account and password

Mail. Send (Debug );

 

// Try {

// Thread. Sleep (1*1000 );

//} Catch (interruptedexception e ){

// E. printstacktrace ();

//}

// Mailbody = new mailbody (Subject + "_" + (I + 1), content );

//}

 

} Finally {

If (null! = Mail)

Mail. Close ();

}

} Catch (addressexception e ){

E. printstacktrace ();

} Catch (messagingexception e ){

E. printstacktrace ();

//} Catch (ioexception e ){

// E. printstacktrace ();

}

}

}

Notes for using javamail to send Emails:

When you use a free email server to send an email, you need to verify the user's identity. The authentication process consumes time, when a user needs to send multiple emails, if the user performs authentication each time, the time consumption is very large;

During the entire mail sending process, session creation only takes one time. That is to say, identity authentication can only be performed once, that is, session = session. getdefaultinstance (props, auth );

The mail sending process is relatively simple. One thing to note is the transport when connecting to the mail server. connect (user. gethost (), user. getUserName (), user. getPassword (); you only need to execute it once. This process consumes a lot of time like authentication.

This program can only send emails with one attachment;

Article Source: http://www.diybl.com/course/3_program/java/javajs/20071226/95325.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.