Javaweb-javamail Mail Development __java

Source: Internet
Author: User
Tags auth base64 imap email account telnet program

The history of email is longer than the web, until now, email is also a very broad application of the Internet services.

Almost all programming languages support sending and receiving e-mail, but wait, before we start coding, it's important to figure out how email works on the internet.

Let's take a look at how traditional mail works. If you are in Beijing now, send a letter to a friend in Hong Kong, how to do it.

First you have to write a letter, put it in an envelope, write an address, put a stamp on it, and then find a post office nearby to keep the letter in.

The letters will be transferred from the nearest small post office to the big Post Office. From the big Post office to other cities, such as the first to Tianjin, and then go to Hong Kong by sea, may also go to the Beijing-Kowloon Line to Hong Kong, but you do not care about specific routes, you need to know one thing, that is, the letter is very slow, at least a few days.

A letter arrives at a post office in Hong Kong and is not sent directly to a friend's house. Because the Post office uncle is very clever, he is afraid your friend is not at home, a trip a Bandi white run, so, the letter will deliver to your friend's mailbox, the mailbox may be in the apartment's one floor, or the house doorway, until your friend comes home to check the mailbox, Once you find the letter, you can get the mail.

e-mail flow is basically the way it works, but the speed is not by day, but in seconds.

Now we go back to email, assuming our own email address is me@163.com, and the email address of the other side is friend@ Sina.com (Note that the address is fictional ha), now we use Outlook or Foxmail and other software to write good mail, fill in each other's email address, point "send", e-mail sent out. These e-mail software is referred to as the Mua:mail user agent--mail users agent.

Email from the MUA, not directly to the other computer, but sent to Mta:mail Transfer agent--mail transmission agent, that is, those email service providers, such as NetEase, Sina and so on. Because our own email is 163.com, so, email was first delivered to the MTA provided by NetEase, and then by the MTA of NetEase to the other service providers, that is, Sina's MTA. There may be other MTAs in the middle of the process, but we don't care about the specific route, we only care about speed.

After the email arrives at Sina's MTA, because the other side is using @sina.com's mailbox, Sina's MTA will post the email to the final destination of the mail mda:mail Delivery agent--mail delivery agent. When the email arrives in the MDA, it lies quietly on a Sina server, stored in a file or special database, which we call the email address for the long-term preservation of the mail.

Similar to ordinary mail, email does not reach the other side of the computer directly, because the other computer does not necessarily boot, the boot is not necessarily connected. To get the message, the other person has to take the message from the MDA to his or her computer via MUA.

So, an email journey is:

Sender-> MUA-> MTA-> MTA-> several MTA-> MDA <-MUA <-Recipients

With these basic concepts, writing programs to send and receive messages is essentially: writing MUA to send messages to the MTA, and writing MUA to collect messages from the MDA.

When you send a message, the protocol used by the MUA and MTA is the Smtp:simple mail Transfer Protocol, and the following MTA to the other MTA also uses the SMTP protocol.

When receiving mail, MUA and MDA use two kinds of protocols: Pop:post Office Protocol, the current version is 3, commonly known as pop3;imap:internet message Access Protocol, the current version is 4, the advantage is not only to take mail, You can also directly manipulate the messages stored on the MDA, such as moving from your inbox to the Trash, and so on.

When the mail client software sends the message, it lets you configure the SMTP server first, which MTA you are sending to. Assuming you're using 163 of your mailbox, you can't send it directly to Sina's MTA, because it only serves Sina's users, so You have to fill in 163. Provided SMTP server address: smtp.163.com, in order to prove that you are 163 users, the SMTP server also requires you to fill in the e-mail address and mailbox password, so that MUA can normally send e-mail through the SMTP protocol to the MTA.

Similarly, when receiving mail from the MDA, the MDA server also asks to verify your mailbox password to ensure that no one is impersonating you to receive your mail, so mail clients such as Outlook will ask you to fill in the POP3 or IMAP server address, email address, and password, so MUA can successfully get messages from the MDA through the POP or IMAP protocol.

Before sending and receiving the mail, please prepare at least two emails, such as xxx@163.com,xxx@sina.com,xxx@qq.com, note that two mailboxes do not use the same mail service provider. 1. Mail protocol 1.1 send and receive mail

e-mail will be all right. Mail is sent from the client to the mail server, the mail message is to download the mail server to the client.

We in 163, 126, QQ, Sohu, Sina and other websites registered email account, in fact, is registered in the mail server. These sites all have their own mail servers. 1.2 Mail Protocol Overview

As with the HTTP protocol, a transport protocol is required to send and receive mail. SMTP: (Simple Mail Transfer Protocol) outgoing mail protocol; POP3: (Post Office Protocol version 3, Post Office Protocol 3rd edition) mail agreement; IMAP: (Internet Message Access Protocol, Internet Message Access Protocol, email protocol, our course does not cover the agreement. 1.3 Understanding the process of sending and receiving mail

In fact, you can understand the mail server as a post office. If you need to send a letter to a friend, you need to put the letter in the mailbox so that your letter will "automatically" arrive at the post Office and the Post Office will mail it to a post office in another province. The letter will then be sent to the addressee's mailbox. Ultimately, the addressee needs to check the mailbox for new letters.

In fact, each mail server consists of an SMTP server and a POP3 server, where the SMTP server is responsible for the request to send the message, and the POP3 is responsible for receiving the mail.

Of course, sometimes we also use 163 of the account, to 126 of the account to send mail. At this point, the message is sent to 126 of the mail server, and for 163 of the mail server does not store this email.

1.4 Mail server name

The SMTP server has a port number of 25 and the server name is smtp.xxx.xxx.
The POP3 server has a port number of 110 and the server name is pop3.xxx.xxx.

For example: 163:smtp.163.com and pop3.163.com; 126:smtp.126.com and pop3.126.com; qq:smtp.qq.com and pop3.qq.com; Sohu:smtp.sohu.com and pop3.sohu.com; sina:smtp.sina.com and pop3.sina.com. 2. Telnet send and receive mail

The Telnet protocol is a member of the TCP/IP protocol family and is the standard protocol and main mode of Internet remote Landing service. It provides users with the ability to complete remote host work on the local computer. Use the Telnet program on the end user's computer to connect to the server. End users can enter commands in the Telnet program, which run on the server as if they were entered directly on the server's console. You can control the server locally. To start a Telnet session, you must enter a username and password to log on to the server. Telnet is a common method of remote control Web server 2.1 BASE64 encryption

BASE64 is a cryptographic algorithm that is reversible. Its role is to make encrypted text can not be identified with the naked eye. Java provides the Sun.misc.BASE64Encoder class for encrypting and decrypting Base64, but we know that using the Sun package will be a warning. Even in eclipse there is no use of this class (need to be set), so we listen to sun Company, do not use its internal use of the class, we use the Apache Commons components in the codec package Base64 this class to complete BASE64 encryption and decryption.

Package cn.itcast;
Import org.apache.commons.codec.binary.Base64;

public class Base64utils {public
    static string encode (string s) {return
        encode (S, ' utf-8 ');
    }

    public static string decode (string s) {return
        decode (S, "utf-8");
    }

    public static string encode (string s, String charset) {
        try {
            byte[] bytes = S.getbytes (charset);
            bytes = base64.encodebase64 (bytes);
            return new String (bytes, charset);
        catch (Exception e) {
            throw new RuntimeException (e);
        }
    }

    public static string decode (string s, String charset) {
        try {
            byte[] bytes = S.getbytes (charset);
            bytes = base64.decodebase64 (bytes);
            return new String (bytes, charset);
        catch (Exception e) {
            throw new RuntimeException (e);
        }
    }
}
2.2 telnet Send mail

Xshell is a powerful security terminal emulation software that supports the Telnet protocol for SSH1, SSH2, and Microsoft Windows platforms. Xshell Secure connections to remote hosts via the Internet and its innovative design and features to help users enjoy their work in a complex network environment

The Xshell can be used in Windows interface to access servers under different remote systems, thus achieving the goal of remotely controlled terminals better.

SMTP server connecting to 163

The following steps are required to send a message after a successful connection:

(1), with the server greeting: EHLO your Name

(2), issued a login request: Auth Login

(3), enter the encrypted mailbox name: (itcast_cxf@163.com) axrjyxn0x2n4zkaxnjmuy29t

(4), enter the encrypted mailbox password: (itcast) aXRjYXN0

(5), enter who to send the mail, namely From:mail from:itcast_cxf@163.com

(6), the input to send the mail to whom, namely TO:RCPT to:itcast_cxf@126.com

(7), Send fill data request:

(8), start input data, data contains: From, to, subject, and the content of the message, if the input end, with a "." is a line that indicates the end of the input:

from:<zhangbozhi@163.com>
to:<itcast_cxf@sina.com>
Subject: I fell in love with you

, I have been deeply in love with you, I am Cecilia Cheung.
.

Notice that there is a blank line between the title and the body of the message. When you want to exit, be sure to use a "." is a single line that indicates the end of the input.

(9), the last step: quit

3. Telnet to receive mail 3.1 telnet to receive mail steps

POP3 eliminates the need to use BASE64 encryption

The server receiving the mail connection is the default port number for the POP3.XXX.COM,POP3 protocol is 110. Please note that. This is quite different from sending an email. If you have a mailbox account in 163, then you want to use Telnet to receive mail, the server you need to connect to is pop3.163.com

Connecting POP3 server: Telnet pop3.163.com 110

Command function Description
User command User username, for example: User itcast_cxf@163.com
Pass Command Pass Itcast, for example:
Stat command The stat command is used to view the number of messages in a mailbox, and the space occupied by all messages
List command The list command is used to view all messages, or to specify the status of the message, for example: List 1 is the size of the first message to view,
List is to view mailing lists, that is, the number of all messages, and size
RETR command View the contents of the specified message, for example: Retr A. View the contents of the first e-mail message
DELE command Mark a message for deletion, but not delete it immediately, but only when it exits
Quit command Exit. If you have already marked some messages with the DELE command before exiting, you will delete them when you exit


4. JavaMail 4.1 JavaMail Overview

Java Mail is a mail-specific API provided by Sun, the main jar package: Mail.jar, Activation.jar.

You need to be careful when you create a Web project using MyEclipse. If there is nothing wrong with using Java Mail in a Web project, publishing to Tomcat is not a problem.
But if you're writing tests in a Web project, that's a problem.

In MyEclipse, the class in the Javax.mail package is automatically imported to the Web project, but not all (but only the interface, not the implementation class of the interface), so the class in MyEclipse cannot run the Java Mail project. But if you are going to import mail.jar yourself, there will be a conflict.

Processing scheme: To the following path to find the Javaee.jar file, remove the Javax.mail ...

D:\Program files\myeclipse\common\plugins\com.genuitec.eclipse.j2eedt.core_10.0.0.me201110301321\data\ Libraryset\ee_5
main classes in 4.2 JavaMail

Main classes in Java Mail: javax.mail.Session, Javax.mail.internet.MimeMessage, Javax.mail.Transport.

Session: Represents a conversation, that is, a session between a client and a mail server. To get a session you need to give the account and password, and of course the server name. The session object in the mail service is equivalent to the Connection object when the database is connected.

MimeMessage: Represents a message class, which is a subclass of messages. It contains the subject (title) of the message, the content, the recipient address, the sender's address, and you can also set up a copy-and-drop, or even an attachment.

Transport: Used to send mail. It is the transmitter. Hello world of 4.3 javamail

When you use Telnet to send mail, you also need to deal with the problem of Base64 encoding yourself, but use javamail to ignore these problems, are handled by JavaMail.

First step: Get session

Session session = Session.getinstance (Properties prop, authenticator auth); 

Where prop needs to specify two key values, one is to specify the server host name, and the other is to specify whether authentication is required. We certainly need certification.

Properties prop = new properties ();
Prop.setproperty ("Mail.host", "smtp.163.com")//Set server host name
prop.setproperty ("Mail.smtp.auth", "true");/setting requires authentication

Where authenticator is an interface representing the authenticator, that is, verifying the identity of the client. We need to implement this interface on our own, and we need to use our account and password to implement this interface.

Authenticator auth = new Authenticator () {public
    passwordauthentication getpasswordauthentication () {
        new Passwordauthentication ("Itcast_cxf", "itcast");/user name and password
    }
};

With the above preparation, you can now get the Session object:

Session session = Session.getinstance (prop, auth);

Step Two: Create the MimeMessage object
Creating MimeMessage requires the session object to be used to create:

MimeMessage msg = new MimeMessage (session);

You then need to set the sender's address, delivery address, subject, and message body.

Msg.setfrom (New InternetAddress ("itcast_cxf@163.com"))/Set sender
msg.addrecipients (recipienttype.to, "itcast_ Cxf@qq.com,itcast_cxf@sina.com ");/set up multiple recipient
msg.addrecipients (recipienttype.cc," itcast_cxf@sohu.com,itcast_ Cxf@126.com ");/set multiple CC
msg.addrecipients (RECIPIENTTYPE.BCC," itcast_cxf@hotmail.com ");/Set Dark send
Msg.setsubject ("This is a test email");/set subject (title)
msg.setcontent ("Of course Hello world!", "text/plain;charset=utf-8");/Set Body

Step three: Send mail

Transport.send (msg);//Send mail
4.4 JavaMail Send a message with an attachment

A message can contain body, attachment n, so the body and N attachments are part of the message.

In the Hello World case above, only messages with body text are sent. So when you call the SetContent () method, you set the body directly, and if you want to send a message with attachments, you need to set the content of the message to be mimemultipart.

Mimemulitpart parts = new Mimemulitpart ()//multi-part object, which can be understood to be a collection of parts
msg.setcontent (parts);//Set the content of the message to be a multiple part content.

Then we need to create the body and N attachments as the principal part object (MimeBodyPart) and add it to the Mimemuiltpart.

MimeBodyPart part1 = new MimeBodyPart ();//Create a part
part1.setcotnent ("This is the body part", "Text/html;charset=utf-8"); Set the content
Parts.addbodypart (part1) to the part, or add the part to the part set.

Below we create an attachment:

MimeBodyPart part2 = new MimeBodyPart ();//Create a part
part2.attachfile ("f:\\a.jpg");/Set Attachment
part2.setfilename (" Hello.jpg ");//Set the attachment name
Parts.addbodypart (part2);//Add attachment to part set

Note that if you set the file name with Chinese in the file name, you need to use the Mimeuitlity class to encode the Chinese:

Part2.setfilename (Mimeuitlity.encodetext ("Belle. jpg"));

public class Javamaildemo {public void SendMail () throws Exception {* * * 1. Get session */Properties
    props = new Properties ();
    Props.setproperty ("Mail.host", "smtp.163.com");

    Props.setproperty ("Mail.smtp.auth", "true"); Authenticator auth = new Authenticator () {@Override protected passwordauthentication Getpasswordauthenticatio
      N () {return new passwordauthentication ("Itcast_cxf", "itcast");

    }
    };

    Session session = Session.getinstance (props, auth); * * 2.
    Create MimeMessage */mimemessage msg = new MimeMessage (session); Msg.setfrom (New InternetAddress ("itcast_cxf@163.com"));/Set Sender msg.setrecipients (recipienttype.to, "itcast_ Cxf@126.com ");/Set recipient msg.setrecipients (recipienttype.cc," itcast_cxf@sohu.com ");/Set cc Msg.setrecipients (Recipie
    NTTYPE.BCC, "itcast_cxf@sina.com");/Set Dark send Msg.setsubject ("This is a test message from Itcast"); Msg.setcontent ("This is a spam message.")

    "," Text/html;charset=utf-8 ");
   /*  * 3.
  e-mail/transport.send (msg);
   /** * Messages with attachments ... * * public void SendMail2 () throws Exception {/* 1. Get session * * Properties props = new properties (
    );
    Props.setproperty ("Mail.host", "smtp.163.com");

    Props.setproperty ("Mail.smtp.auth", "true"); Authenticator auth = new Authenticator () {@Override protected passwordauthentication Getpasswordauthenticatio
      N () {return new passwordauthentication ("Itcast_cxf", "itcast");

    }
    };

    Session session = Session.getinstance (props, auth); * * 2.
    Create MimeMessage */mimemessage msg = new MimeMessage (session); Msg.setfrom (New InternetAddress ("itcast_cxf@163.com"));/Set Sender msg.setrecipients (recipienttype.to, "itcast_


    Cxf@126.com ");/Set recipient Msg.setsubject (" This is a test message from Itcast has an attachment ");
     * * When sending a message that contains an attachment, the message body is a multiple-part form. * 1. Create a part content for a multiple part. Mimemultipart * Mimemultipartis a collection that is used to load multiple body parts. * 2.
     We need to create two body parts, one is text content and the other is attached. * Main part is called MimeBodyPart * 3.
     Set the Mimemultipart to the contents of the MimeMessage. */Mimemultipart list = new Mimemultipart ()//Create multiple content//create MimeBodyPart MimeBodyPart part1 = new MimeBodyPart
    ();
    Set the contents of the principal part part1.setcontent ("This is a spam message containing attachments", "text/html;charset=utf-8");


    Add the main part to the set List.addbodypart (part1);
    Create MimeBodyPart MimeBodyPart part2 = new MimeBodyPart (); Part2.attachfile (New file ("f:/f/bai Bing. jpg"))//Set the contents of the attachment//Set the name of the file displayed, where Encodetext is used to handle the Chinese garbled problem Part2.setfilename (mimeutil
    Ity.encodetext ("Great beauty. jpg"));

    List.addbodypart (part2);


    Msg.setcontent (list)//set it to the message as the content of the message. * * 3.    
  e-mail/transport.send (msg); public void SendMail3 () throws Exception {/* 1. Get session/Session session = Mailutils.creates
    Ession ("smtp.163.com", "ITCAST_CXF", "itcast");
   /*  * 2. Create a Message object/mail mail = new mail ("itcast_cxf@163.com", "itcast_cxf@126.com,itcast_cxf@sina.com", "no What is junk mail?

    "," Here is the Body ");
    * * Create two Attachment objects/Attachbean AB1 = new Attachbean (New File ("f:/f/bai Bing. jpg"), "little beauty. jpg");

    Attachbean ab2 = new Attachbean (New File ("F:/f/big.jpg"), "my Down jacket. jpg");
    Add to mail in Mail.addattach (AB1);

    Mail.addattach (AB2); * * 3.
  Send * * * mailutils.send (session, mail); }
}
5. Mailutils
public class Mailutils {public static session createsession (string host, final string username, final string password
        {Properties prop = new properties (); Prop.setproperty ("Mail.host", host);//Specify Host Prop.setproperty ("Mail.smtp.auth", "true");//specify validation to TRUE//create Validator Authenticator auth = new Authenticator () {public passwordauthentication getpasswordauthentication
            () {return new passwordauthentication (username, password);

        }
        };
    Gets the Session object return Session.getinstance (prop, auth);  /** * Send the specified message * * @param mail/public static void Send (Sessions session, final mail mail)
        Throws Messagingexception, IOException {mimemessage msg = new MimeMessage (session);//Create mail Object Msg.setfrom (New InternetAddress (Mail.getfrom ()))//Set sender msg.addrecipients (recipienttype.to, Mail.gettoaddress (
      )//Set recipient//Set CC  String cc = mail.getccaddress ();
        if (!cc.isempty ()) {msg.addrecipients (recipienttype.cc, CC);
        //Set Dark send String bcc = mail.getbccaddress ();
        if (!bcc.isempty ()) {msg.addrecipients (recipienttype.bcc, BCC);

        Msg.setsubject (Mail.getsubject ());//Set theme Mimemultipart parts = new Mimemultipart ();//Create a part set object MimeBodyPart part = new MimeBodyPart ();//Create a widget Part.setcontent (Mail.getcontent (), "text/html;charset=utf-8"); /Set the message text content Parts.addbodypart (part)//Add parts to the part set/////////////////////////////////////////////
            Add attachment list<attachbean> attachbeanlist = Mail.getattachs ();//Get All attachments if (attachbeanlist!= null) { 
                for (Attachbean attach:attachbeanlist) {MimeBodyPart Attachpart = new MimeBodyPart ();//Create a part Attachpart.attachfile (Attach.getfile ());//Set Attachment file Attachpart.setfilename (MimeUtility.encodetext (Attach. GetFileName ()))//Set attachment file name Parts.addbodypart (attachpart
            ); } msg.setcontent (parts);//set Content Transport.send (msg) for message;//Send Mail}}

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.