Use JavaMail to send a simple message __java

Source: Internet
Author: User
Tags auth dsn starttls static class server port

It programmer development must-all kinds of resources download list, the most complete IT resources in history, personal collection summary.
What is Java Mail

(1) to write their own programs to send and receive mail, you can directly use the socket programming connected to the Remote mail server, and then according to the Mail protocol and mail server interaction, involving more details. In addition, it is a very difficult and troublesome task to create a complex MIME-formatted message yourself.
(2) JavaMail is a set of standard development packages that Sun provides to enable Java developers to deliver and receive mail in their applications, and it supports a number of commonly used mail protocols, such as SMTP, POP3, and IMAP.
(3) When developers use the JavaMail API to write mail processing software, they do not need to consider the underlying implementation details of the mail protocol, just call the corresponding API class in the JavaMail development package.
(4) JavaMail also provides APIs that enable the creation of content in a variety of complex MIME format messages.

Architecture and API classification of JavaMail


(1) The JavaMail API can usually be divided into three main categories according to its function:
The Api:message class for creating and parsing message content is the core API for creating and parsing messages, and its instance objects represent an e-mail message. The Api:transport class that sends the message is the core API class that sends the message, and its instance object represents the message sending object that implements a mail delivery protocol, such as the SMTP protocol. The Api:store class that receives the message is the core API class that receives the message, and its instance object represents a message recipient object that implements a message receipt protocol, such as the POP3 protocol.

(2) Session class
The session class is used to define the environment information required by the entire application and to collect information about the sessions of the client that establish a network connection to the mail server, such as the host name of the mail server, the port number, the message sending and receiving protocols used, and so on. The session object builds the transport and store objects that are used to send and receive messages based on this information, and provides information support when creating a message object for the client.

Mail Sending program
(1) Use JavaMail to send a simple message:
Creates a session object that contains network connection information for the mail server. Creates a Message object that represents the content of the messages. Create a Transport object, connect to the server, send a message, and close the connection.

(2) Application of authenticator class to implement user information verification
Combined with Transport.send static method.

Mode 1:

Sendmessagedemo1.java

Package edu.mail.util;
Import java.util.Properties;
Import javax.mail.Address;
Import Javax.mail.Message;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.InternetAddress;

Import Javax.mail.internet.MimeMessage; public class SendMessageDemo1 {public static void main (string[] args) throws Exception {//To create a session containing network connection information for the mail server
	  Object.
	  Properties Props = new properties (); 
	  Set to TRUE to require authentication with the login method, the default is False Props.setproperty ("Mail.smtp.auth", "true");
	  Set the Protocol Props.setproperty ("Mail.transport.protocol", "SMTP") to connect to the server;
	  Session session = Session.getinstance (props);
	  
Session.setdebug (TRUE);
	  Creates a Message object that represents the content of the messages.
	 msg = new MimeMessage (session); This may be a special requirement for 163 mailboxes, mail from must equal authorized user, so from must be the same as the logged-on user name Msg.setfrom (new InternetAddress ("
	  Xh216319@163.com "));
	  Msg.settext ("This is the the" the "the");

Msg.setsubject ("SendMessageDemo1"); 
	  Create a Transport object, connect to the server, send a message, and close the connection. Transport traNsport = Session.gettransport ();
	    Set up a connected mail server and its ports, as well as the connected username and password Transport.connect ("smtp.163.com", "xh216319", "Xiaoxiao"); * * TRANSPORT.SEND (message) and transport.
	     SendMessage (message) difference * 1. The Send () method of the static class transport contains three things: connecting to the server, sending mail, shutting down the server.
	     * 2. The SendMessage () method for instance transport is simply to send a message.
	     * Therefore, transport.send (message) cannot be used here.
	     * But if it is a mass mailing, it is best not to use static transport.send (message), because it sends a mail will be connected to the server once, this is less efficient.
	  */Transport.sendmessage (msg, new Address[]{new internetaddress ("itstar1965@sina.com")});
	   
   Transport.close ();
 }
}

Mode 2 (Apply authenticator class to implement user information authentication):

Package edu.mail.util;
Import Java.util.Date;
Import java.util.Properties;
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.MimeMessage;
	   public class SendMessageDemo2 {public static void main (string[] args) throws Exception {//Create a Session object that contains network connection information for the mail server.
	   Properties Props = new properties ();
	   Props.setproperty ("Mail.transport.protocol", "SMTP");
	   Props.setproperty ("Mail.host", "smtp.163.com");
	   Props.setproperty ("Mail.smtp.auth", "true"); The difference between the/** * getinstance () and Getdefaultinstance () methods: * getinstance () creates a new session object each time it is invoked and returns the * Getdefaultinstance ( The first call returns a Session object and sets it to the default, and when the method is invoked the second time, the default Session object **///Because the authenticator class is an abstract class, you can only ne in the form of an anonymous inner class W A authenticator of the subclass object, and overrides its Getpasswordauthentication () method session SEssion = session.getinstance (props, New authenticator () {protected passwordauthentication
    	     Thentication () {Return to New Passwordauthentication ("xh216319", "Xiaoxiao");
       }
		}
       );
Set debug mode to print execution Session.setdebug (true);
	   Creates a Message object that represents the content of the messages.
	   msg = new MimeMessage (session);
	   Msg.setfrom (New InternetAddress ("xh216319@163.com")); Use the Internetaddress.parse () method to flexibly encapsulate a string object as a internetaddress array msg.setrecipients (recipienttype.to,
	   Internetaddress.parse ("itstar1965@sina.com,xh216319@163.com"));
	   Msg.setsubject ("SendMessageDemo2");
	   Msg.setsentdate (New Date (100000)); Msg. SetText () is to display all of the content as text, ignoring the HTML tags in it, and msg.setcontent () can set the content to display in the specified format msg.setcontent ("<span style= ' color:red '"
> This is to use authenticator class to achieve user information authentication javamail</span> "," text/html;charset=utf-8 ");
	   Create a Transport object, connect to the server, send a message, and close the connection.
	There is no need to specify the address to send, which will go to address transport.send (msg) of the Recipients property of the Message object; }

}
 

Environment Properties of the session

Property Description Default Value
Mail.store.protocol Specifies the default message Access Protocol. The Session.getstore () method is returns a Store object that implements this protocol. The client can override this property and explicitly specify the protocol with the Session.getstore (String protocol) Metho D. The appropriate protocol in the Config files
Mail.transport.protocol Specifies the default transport Protocol. The Session.gettransport () method returns a transport object to implements this protocol. The client can override this property and explicitly specify the protocol by using Session.gettransport (String protocol) m Ethod. The appropriate protocol in the Config files
Mail.host Specifies the default Mail server. The Store and transport object ' s Connect methods use this property, if the Protocol-specific host property is absent, to L Ocate the target host. The Local Machine
Mail.user Specifies the username to provide is connecting to a Mail server. The Store and transport object ' s Connect methods use this property, if the Protocol-specific username property is absent, To obtain the username. User.Name
Mail.protocol.host Specifies the protocol-specific default Mail server. This is overrides the Mail.host property. Mail.host
Mail.protocol.user Specifies the protocol-specific default username for connecting to the Mail server. This is overrides the Mail.user property. Mail.user
Mail.from Specifies the "return" to the current user. Used by the "internetaddress.getlocaladdress" to specify the "Current user" email address. Username@host
Mail.debug Specifies the initial debug mode. Setting This property to True would turn on debug mode while Setting it to false turns debug mode. False


SMTP protocol-related environment variables Package COM.SUN.MAIL.SMTP

Name Type Description
Mail.smtp.user String Default user name for SMTP.
Mail.smtp.host String The SMTP server to connect to.
Mail.smtp.port Int The SMTP server port to connect to, if the Connect () method doesn ' texplicitly specify one. Defaults to 25.
Mail.smtp.connectiontimeout Int Socket connection timeout value in milliseconds. The Default is infinite timeout.
Mail.smtp.timeout Int Socket I/O timeout value in milliseconds. The Default is infinite timeout.
Mail.smtp.from String Email address to use for SMTP MAIL command. This is sets the Envelopereturn address. Defaults to Msg.getfrom () orinternetaddress.getlocaladdress (). NOTE:mail.smtp.user is previouslyused for this.
Mail.smtp.localhost String The local host name used in the SMTP HELO or EHLO command. Defaults to Inetaddress.getlocalhost (). GetHostName (). Should not normally need tobe set if your JDK and your name service are configured.
Mail.smtp.localaddress String Local address (host name) to bind to when creating the SMTP socket. Defaults to the "address" picked by the Socket class. Should not normally need to being set, but useful with multi-homed hostswhere it ' s important to pick a particular local addre SS to bind to.
Mail.smtp.localport Int Local port number to bind to when creating the SMTP socket. Defaults to the port number picked by the Socket class.
Mail.smtp.ehlo Boolean If false, don't attempt to sign in with the EHLO command. Defaults Totrue. Normally failure of the EHLO command would fallback to the Helocommand; This property is exists to servers that don ' t fail ehloproperly or don ' t implement EHLO.
Mail.smtp.auth Boolean If true, attempt to authenticate the user using the AUTH command. Defaults to False.
Mail.smtp.submitter String The submitter to use in the "AUTH" tag in the "MAIL from command." Typically used by a mail relay to pass along information about theoriginal submitter of the. Also theSetsubmittermethod of smtpmessage.mail clients typically do not use this.
Mail.smtp.dsn.notify String The NOTIFY option to the RCPT command. Either NEVER, or somecombination of SUCCESS, failure, and DELAY (separated by commas).
Mail.smtp.dsn.ret String The RET option to the MAIL command. Either full or HDRS.
Mail.smtp.allow8bitmime Boolean If set to True, and the server supports the 8BITMIME extension, textparts of messages which use the "quoted-printable" or " Base64 "Encodingsare converted to use" 8bit "encoding if they follow the RFC2045 rulesfor 8bit text.
Mail.smtp.sendpartial Boolean If set to True, and a message has some valid and some invalidaddresses, send the message anyway, reporting the partial FAI Lure Witha Sendfailedexception. If set to False (the default), the message IsNot sent to any of the recipients if there are an invalid recipientaddress.
Mail.smtp.sasl.realm String The realm to use with DIGEST-MD5 authentication.
Mail.smtp.quitwait Boolean If set to False, the QUIT command are sentand the connection is immediately closed. If set to True (the default), causes the "transport to waitfor" response to the QUIT command.
Mail.smtp.reportsuccess Boolean If set to True, causes the "transport to include ansmtpaddresssucceededexceptionfor" is successful. Note also which this would cause asendfailedexceptionto be thrown from theSendmessagemethod-if all a Ddresses were correct and the message was sentsuccessfully.
Mail.smtp.socketFactory.class String If Set, specifies the name of a class that implements Thejavax.net.SocketFactory interface. This classwill is used to create SMTP sockets.
Mail.smtp.socketFactory.fallback Boolean If set to True, failure to create a socket using the Specifiedsocket factory class would cause the socket to be created USI Ngthejava.net.Socket class. Defaults to True.
Mail.smtp.socketFactory.port Int Specifies the port to connect to when using the specified socketfactory. If not set, the default port would be used.
Mail.smtp.mailextension String Extension string to append to the MAIL command. The extension string can be used to specify standard Smtpservice extensions as as. vendor-specific extensions. Typically the application should use Thesmtptransportmethodsupportsextensionto Verify this server supports the DES ired service extension. SEERFC 1869and RFCs that define specific extensions.
Mail.smtp.starttls.enable Boolean If True, enables the STARTTLS command (ifsupported by the server) to switch the connection to a Tls-protectedco Nnection before issuing any login commands. Note This Appropriatetrust store must configured so the client would trust the server ' Scertificate. Defaults to False.
Mail.smtp.userset Boolean If set to True, use the RSET command instead of the NOOP Commandin the isconnected method. In some cases sendmail'll respond slowly after many NOOP commands;use of RSET avoids this sendmail issue. Defaults to False.
Mail.smtp.ssl.protocols String Specifies the SSL protocols that is enabled for SSL connections. The property value is a whitespace separated list of tokens Acceptableto thejavax.net.ssl.SSLSocket.setEnabledProtocols me Thod.
Mail.smtp.ssl.ciphersuites String Specifies the SSL cipher suites that is enabled for SSL connections. The property value is a whitespace separated list of tokens Acceptableto Thejavax.net.ssl.SSLSocket.setEnabledCipherSuite S method.




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.