Simple Java mail instance code

Source: Internet
Author: User

In this article, we recommend three simple Java mail instance codes, which use the java code that comes with apache. We can simply send emails or attachments, for your reference.

 

Here we use apache commons-e-mail (http://commons.apache.org/proper/commons-email/download_email.cgi) and java mail () to send mail.
My only requirement is to send an alarm email when a system exception occurs. Therefore, the code is very simple without attachments:

 

The Code is as follows: Copy code
Public static void sendMail (String receiverAddress, String subject, String message)
{
MultiPartEmail email = new MultiPartEmail ();
Try {
// Smtp server:
Email. setHostName ("smtp.163.com ");
// Charset
Email. setCharset ("UTF-8 ");
// Explorer's address
Email. addTo (receiverAddress );
// Sender's email
Email. setFrom ("*** @ 163.com ");
// Account password
Email. setAuthentication ("***","***");
// Subject
Email. setSubject (subject );
// Information
Email. setMsg (message );
// Send
Email. send ();
} Catch (EmailException e ){
E. printStackTrace ();
}
}

Method 2

The Code is as follows: Copy code

Package mail;

Import java. util. Date;
Import java. util. Properties;
Import javax. mail. Address;
Import javax. mail. Authenticator;
Import javax. mail. Message;
Import javax. mail. PasswordAuthentication;
Import javax. mail. Session;
Import javax. mail. Transport;
Import javax. mail. internet. InternetAddress;
Import javax. mail. internet. MimeMessage;

/***//**
* Send a common email, send an email with an attachment to a common email, and receive an html-based email from an email with an attachment, the following is a summary of emails with images sent in html format.
*/
Public class Test
{
// Email server
Private String host = "smtp.163.com ";
// This is your email user name
Private String username = "******";
// Your email password
Private String password = "******";

Private String mail_head_name = "this is head of this mail ";

Private String mail_head_value = "this is head of this mail ";

Private String mail_to = "zdw@live.cn ";

Private String mail_from = "***** @ 163.com ";

Private String mail_subject = "this is the subject of this test mail ";

Private String mail_body = "this is the mail_body of this test mail ";

Private String personalName = "my emails ";

Public Test ()
{
}

/***//**
* This code is used to send a common email.
*/
Public void send () throws Exception
{
Try
{
Properties props = new Properties (); // obtain the system environment
Authenticator auth = new Email_Autherticator (); // Authenticator
Props. put ("mail. smtp. host", host );
Props. put ("mail. smtp. auth", "true ");
Session session = Session. getDefaultInstance (props, auth );
// Set the session to communicate with the email server.
MimeMessage message = new MimeMessage (session );
// Message. setContent ("foobar," application/x-foobar "); // you can specify the mail format.
Message. setSubject (mail_subject); // you can specify a subject.
Message. setText (mail_body); // you can specify the mail body.
Message. setHeader (mail_head_name, mail_head_value); // you can specify the mail title.
Message. setSentDate (new Date (); // you can specify the mail sending Date.
Address address = new InternetAddress (mail_from, personalName );
Message. setFrom (address); // you can specify the sender's address.
Address toAddress = new InternetAddress (mail_to); // you can specify the email receiver Address.
Message. addRecipient (Message. RecipientType. TO, toAddress );
Transport. send (message); // send an email
System. out. println ("send OK! ");
} Catch (Exception ex)
{
Ex. printStackTrace ();
Throw new Exception (ex. getMessage ());
}
}

/***//**
* Used for server-to-user authentication
*/
Public class Email_Autherticator extends Authenticator
{
Public Email_Autherticator ()
{
Super ();
}

Public Email_Autherticator (String user, String pwd)
{
Super ();
Username = user;
Password = pwd;
}

Public PasswordAuthentication getPasswordAuthentication ()
{
Return new PasswordAuthentication (username, password );
}
}

Public static void main (String [] args)
{
Test sendmail = new Test ();
Try
{
Sendmail. send ();
} Catch (Exception ex)
{
}
}

}

Attached

The Code is as follows: Copy code

Package com. li72.email;
Import java. util. Date;
Import java. util. Properties;
Import javax. activation. DataHandler;
Import javax. activation. DataSource;
Import javax. activation. FileDataSource;
Import javax. mail. Authenticator;
Import javax. mail. Message;
Import javax. mail. PasswordAuthentication;
Import javax. mail. Session;
Import javax. mail. Transport;
Import javax. mail. Message. RecipientType;
Import javax. mail. internet. InternetAddress;
Import javax. mail. internet. MimeBodyPart;
Import javax. mail. internet. MimeMessage;
Import javax. mail. internet. MimeMultipart;

Public class AnthoerSimpleEmail {
@ SuppressWarnings ("deprecation ")
Public static void main (String [] args) throws Exception {
Properties props = new Properties ();
Props. setProperty ("mail. smtp. auth", "true"); // a common client is required.
Props. setProperty ("mail. transport. protocol", "smtp"); // You must select a protocol.
Props. setProperty ("mail. host", "smtp.163.com ");
Session session = Session. getDefaultInstance (props, new Authenticator (){
@ Override
Protected PasswordAuthentication getPasswordAuthentication (){
// TODO Auto-generated method stub
Return new PasswordAuthentication ("sender email", "password ");
}
});
Session. setDebug (true );
Message msg = new MimeMessage (session );
MimeMultipart mimeMultipart = new MimeMultipart ();
MimeBodyPart mimeBodyPart = new MimeBodyPart ();
MimeBodyPart. setText ("hello ");
MimeBodyPart attach1 = new MimeBodyPart ();
MimeMultipart. addBodyPart (mimeBodyPart );
DataSource ds1 = new FileDataSource ("F: \ level 6 .txt ");
DataHandler dh1 = new DataHandler (ds1 );
Attach1.setDataHandler (dh1 );
Attach1.setFileName ("reg.txt ");
MimeMultipart. addBodyPart (attach1 );
Msg. setContent (mimeMultipart );
Msg. saveChanges ();
Msg. setFrom (new InternetAddress ("sender "));
Date d = new Date ();
Msg. setSubject ("" + d. getDate ());
Msg. setRecipient (RecipientType. TO, new InternetAddress ("recipient "));
Transport. send (msg );
}
}

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.