An example of sending an email using javamail)

Source: Internet
Author: User

First, introduce the J2EE package path to classpath. If you have installed JBuilder, you can find it in its installation path lib directory.
To mail. jar and activation. jar, add these two packages to the system environment variables, even if JBuilder is not used for development.
Used.

Program:

Import java. Io .*;
Import java. util .*;
Import javax. Mail .*;
Import javax. Mail. Internet .*;

/**
* <P> title: simple mailbean </P>
* <P> Description: provides a simple mail sending function (/P>
* <P> copyright: Copyright (c) 2003 </P>
* @ Version 1.0
*/

Class extendstring {
Public extendstring (){
}
/**
Remove the blank characters at both ends of the string and convert the string to a Chinese string of the standard character gb2312.
*/
Public String CS (string Str) {// remove the white space character from string 2
Try {
If (STR = NULL)
Return "";
STR = Str. Trim ();
If (STR = NULL)
Return "";
STR = new string (Str. getbytes ("8859_1"), "GBK ");
}
Catch (exception e ){
System. Out. println (E );
}
Return STR;
}

}

Public class sendmail
{
Private string errmsg = "";
Private extendstring exstr = new extendstring ();

Private string sender = ""; // sender address
Private string smtphost = ""; // mail sending server (SMTP)
Private string user = ""; // logon Username
Private string Password = ""; // logon Password

Private string subject = ""; // mail topic

Public Sendmail ()
{
This. setpropertiesattri ();
}

Private void setpropertiesattri ()
{
Try
{
Inputstream is = getclass (). getresourceasstream ("MailServer. properties ");
Properties prop = new properties ();
Prop. Load (is );

This. setsmtphost (prop. Get ("smtphost"). tostring ());
This. setuser (prop. Get ("user"). tostring ());
This. setpassword (prop. Get ("password"). tostring ());
This. setsender (prop. Get ("sender"). tostring ());
This. setsubject (exstr. CS (prop. Get ("subject"). tostring ()));
}
Catch (exception ex)
{
System. Err. println ("ex1 in sendmail. Java:" + ex. tostring ());
}
}
/** Set the sender address */

Public void setsender (string sender)
{
This. Sender = sender;
}

Public String getsender ()
{
Return sender;
}

/** Set the mail sending server (SMTP )*/
Public void setsmtphost (string smtphost) {This. smtphost = smtphost ;}
Public String getsmtphost () {return smtphost ;}

/** Set the logon user name */
Public void setuser (string user)
{
This. User = user;
}
Public String getuser ()
{
Return user;
}

/** Set the logon password */
Public void setpassword (string password)
{
This. Password = password;
}
Public String GetPassword ()
{
Return password;
}

/** Set mail subject */
Public void setsubject (string subject)
{
This. Subject = subject;
}
Public String getsubject ()
{
Return subject;
}

/**
* Use SMTP to send mail to the main program
* @ Throws messagingexception mail failed to send
*/
Public void SMTP (string receiver er, string content) throws messagingexception
{
If (smtphost = NULL) throw new messagingexception ("smtphost not found ");
If (user = NULL) throw new messagingexception ("user not found ");
If (Password = NULL) throw new messagingexception ("password not found ");

Properties Properties = new properties ();
Properties. Put ("mail. SMTP. Host", smtphost); // set the SMTP host
Properties. Put ("mail. SMTP. Auth", "true"); // use SMTP for authentication

Session session = session. getdefaultinstance (properties,
New authenticator (){
Public passwordauthentication getpasswordauthentication (){
Return new passwordauthentication (user, password );
}
});

// Obtain the email Session Object
Mimemessage mimemsg = new mimemessage (session); // create a mime mail object
If (sender! = NULL) // set the sender address
{
Mimemsg. setfrom (New internetaddress (sender ));
}
If (else er! = NULL) // set the recipient address
{
Mimemsg. setrecipients (message. recipienttype. To, parse (receiver ER ));
}
If (subject! = NULL) // set the Email Subject
{
Mimemsg. setsubject (subject, "GBK ");
}
Mimebodypart part = new mimebodypart (); // mail content section
Part. settext (content = NULL? "": Content, "GBK ");

// Set the email format to html cqc.
Part. setcontent (content. tostring (), "text/html; charset = GBK ");
Multipart = new mimemultipart ();
Multipart. addbodypart (part); // Add the mail content section to multipart.
Mimemsg. setcontent (multipart); // Add the multipart to the information body.
Mimemsg. setsentdate (new date (); // you can specify the sending date.
Transport. Send (mimemsg); // send an email
}

/** Resolve the address set string */
Private internetaddress [] parse (string addressset) throws addressexception
{
Arraylist list = new arraylist ();
Stringtokenizer tokens = new stringtokenizer (addressset ,";");
While (tokens. hasmoretokens ())
{
List. Add (New internetaddress (tokens. nexttoken (). Trim ()));
}
Internetaddress [] addressarray = new internetaddress [list. Size ()];
List. toarray (addressarray );
Return addressarray;
}

/**
* Interfaces for external calls
*/

Public Boolean sendmails (string mail, string content)
{
Int maillen = 0;
Int contentlen = 0;
If (Mail = NULL | content = NULL)
{
Return false;
}

Try
{
This. SMTP (Mail, content );
}
Catch (exception ex)
{
System. Err. println ("ex2 in sendmail. Java:" + ex. tostring ());
}

Return true;
}

Public static void main (string [] ARGs)
{
Sendmail mail = new Sendmail ();
String email = "csdn@csdn.net; tom@163.com ";
String content = "account: 123 password: 123 <br/> Thank you for registering! <Br/> <a href = 'HTTP: // www.xxxx.com.cn 'target = '_ blank'> www.xxxx.com.cn </a> <br/> XXXX <br/> today ";
Try
{
Mail. sendmails (email, content );
}
Catch (exception ex)
{
System. Err. println ("ex33:" + ex. tostring ());
}
}

}

After compilation, create a text file MailServer. properties in the directory of the class file,
Format:
Smtphost = smtp.163.com
User = user
Password = pwd
Sender = csdn@csdn.com
Subject = Hello

Run the program to send emails!

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.