Use JavaMail to send messages based on Java _java

Source: Internet
Author: User
Tags character set mail account microsoft outlook mail microsoft outlook

I. Concepts related to Mail

Mail protocol. Mainly include:

SMTP protocol: Simple Mail Transfer Protocol, which is used to send e-mail messages

POP3 protocol: Post Office Protocol 3, the third version of the Post Office agreement, for receiving mail

IMAP protocol: Internet Message Access Protocol, the Internet Messaging Access Protocol, is a POP3 alternative protocol

--------------------------------------------------------------------------------

Ii. Build James Mail server

James is an open source project for Apache, pure Java implementation

Build the James Server

① Download Apache-james-2.3.2.zip Decompression

② run the Run.bat under the Bin directory to start the server [Telnet localhost 4555]

③ Server configuration via Apps\james\sar-inf\config.xml

Note: First go to the bin run together. Put the Telnet client on the control Panel as a non-Chinese directory

--------------------------------------------------------------------------------

Third, install outlook[mail client]

Product secret key: PQDV9-GPDV4-CRM4D-PHDTH-4M2MT

Create a user account

A remote administration Tool that uses Telnet to connect James

Two, log in as an administrator

Iii. adding users using the AddUser command

--------------------------------------------------------------------------------

Iv. Configuring Outlook mail clients

For easy viewing, you can configure the Microsoft Outlook mail client to ensure that the James Mail server is up and running, starting Microsoft Outlook.

Select Tools-> Options to open the Options panel. Select "Mail Settings" and click "E-mail Account" to open the "Account Settings" panel. Create a new mail account under the E-mail tab

--------------------------------------------------------------------------------

V. Case [build James Mail server]

Requirements Description:

Set up the James Mail server on this machine and customize the name of the server.

Create two test users.

Configure one of the test users for Outlook mail accounts in Microsoft Outlook

--------------------------------------------------------------------------------

Vi. use JavaMail to send e-mail (case)

Demand:

Using JavaMail technology, to send an email from account A to account B, titled "Meeting Notice", the message reads "XX Hello!" Please come to the conference room at B01 tomorrow 16:00 to convene a technical seminar. "To see if a message sent by a mail program through an Outlook client is sent successfully

Key code:

Create a class Emailauthenticator and inherit from authenticator, and embed user name and password

Create mail class to set message information:

public class Mail {private String mailserver,from,to,mailsubject,mailcontent;

 Private String Username,password;

   Public mail () {//Set mail message//Authenticate login username username= "hq@mail.com";

   Authentication password password= "HQ";

   Certified mailbox corresponding to the mail server mailserver= "192.168.17.176";

   Sender information from= "WJ";

   Recipient information to= "wj@mail.com";

   Mail title mailsubject= "We Are all good kids 333"; Message content mailcontent= "This is a test email!"

 If there is a similarity, it is purely impossible ";

   //Set the mail server @SuppressWarnings ("static-access") public void Send () {Properties prop=system.getproperties ();

    

   Specify Mail server Prop.put ("Mail.smtp.host", mailserver);

    

   Whether to open the authentication prop.put ("Mail.smtp.auth", "true");

   Prop.put of the SMTP protocol ("Mail.smtp.port", "25");

   Generate session Service Emailauthenticator Mailauth=new emailauthenticator (username, password);

    Session mailsession=session.getinstance (prop, (authenticator) mailauth);

      

      try {//Encapsulate Message Object message message=new mimemessage (mailsession); Message. Setfrom (New InternetAddress (from)); Sender Message.setrecipient (Message.RecipientType.TO, New internetaddress (to));//Recipient Message.setsubject (mails

      Ubject);

      Set content (setting character set handling garbled problem) Message.setcontent (mailcontent, "TEXT/HTML;CHARSET=GBK");

      Message.setsentdate (New Date ());

      Create transport instance, send mail transport tran=mailsession.gettransport ("SMTP");

      Tran.send (Message,message.getallrecipients ());

      

    Tran.close ();

    catch (Exception e) {e.printstacktrace (); 
 }

 }

Test class:

public class MyTest {public

  static void Main (string[] args) {

    mail mail=new mail ();

    Mail.send ();

    System.out.println ("success!");

  }
 

--------------------------------------------------------------------------------

Vii. Send mail with attachments

public class Mailwithattachment {private Javamailsender mailsender;//must use Javamailsender public void Setmailsende

  R (Javamailsender mailsender) {this.mailsender = MailSender; public void Send () throws messagingexception,ioexception{mimemessage mimemessage = Mailsender.createmimeme

    Ssage ();

    Mimemessagehelper helper = new Mimemessagehelper (MimeMessage, True, "UTF-8");

    Helper.setfrom ("hq@mail.com");

     

    Helper.setto ("wj@mail.com");

    Helper.setsubject ("hahaha"); Helper.settext ("Smile every day, happy heart!!!

    ");

    Add Attachment 1 Classpathresource file1 = new Classpathresource ("/cn/bdqn/attachfiles/test.doc");

    Helper.addattachment (File1.getfilename (), File1.getfile ()); Add Attachment 2: The file name of the attachment is Chinese, you need to encode the file name conversion, solve the garbled problem classpathresource file2 = new Classpathresource ("/CN/BDQ

    n/attachfiles/attachment test file. doc ");

    Helper.addattachment (Mimeutility.encodeword (File2.getfilename ()), File2.getfile ()); Mailsender.send(MimeMessage); 

 }

}

Test class:

public class MailTest {public

  static void Main (string[] args) {

    ApplicationContext context = new CLASSPATHXMLAPPL Icationcontext ("Applicationcontext.xml");

     

    /* Test message with attachment/

    try{

      mailwithattachment Mailwithattach = (mailwithattachment) Context.getbean (" Mailwithattachment ");

      Mailwithattach.send ();

    } catch (Exception e) {

      System.out.print (e.tostring ());

    }

  }

}  

Applicationcontext.xml: Large Configuration

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.