现在的位置: 首页 > 综合 > 正文

使用JavaMail发送一封简单的邮件

2017年11月19日 ⁄ 综合 ⁄ 共 10237字 ⁄ 字号 评论关闭

IT程序员开发必备-各类资源下载清单,史上最全IT资源,个人收藏总结!

什么是Java Mail

  (1)要自己写程序发送和接收邮件,可以直接采用Socket编程连接上远程的邮件服务器,然后按照邮件协议与邮件服务器进行交互,涉及较多细节。另外,要想自己编程创建出复杂的MIME格式的邮件,是一件非常困难和麻烦的事情。
  (2)JavaMail 是Sun公司为方便Java开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发包,它支持一些常用的邮件协议,如SMTP、POP3、IMAP。
  (3)开发人员使用JavaMail API编写邮件处理软件时,无须考虑邮件协议的底层实施细节,只要调用JavaMail开发包中相应的API类就可以了。
  (4)JavaMail 也提供了能够创建出各种复杂MIME格式的邮件内容的相关API。

JavaMail 的体系结构与API分类

 
  (1)JavaMail API按其功能划分通常可分为如下三大类:

  • 创建和解析邮件内容的API :Message类是创建和解析邮件的核心API,它的实例对象代表一封电子邮件。
  • 发送邮件的API:Transport类是发送邮件的核心API类,它的实例对象代表实现了某个邮件发送协议的邮件发送对象,例如SMTP协议。
  • 接收邮件的API:Store类是接收邮件的核心API类,它的实例对象代表实现了某个邮件接收协议的邮件接收对象,例如POP3协议。

  (2)Session类

  • Session类用于定义整个应用程序所需的环境信息,以及收集客户端与邮件服务器建立网络连接的会话信息,如邮件服务器的主机名、端口号、采用的邮件发送和接收协议等。Session对象根据这些信息构建用于邮件收发的Transport和Store对象,以及为客户端创建Message对象时提供信息支持。

邮件发送程序
 (1)使用JavaMail发送一封简单的邮件:

  • 创建包含邮件服务器的网络连接信息的Session对象。
  • 创建代表邮件内容的Message对象。
  • 创建Transport对象、连接服务器、发送Message、关闭连接。

 (2)应用Authenticator类实现用户信息验证

  •  结合Transport.send静态方法使用。

方式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 {
	 
//创建包含邮件服务器的网络连接信息的Session对象。
	  Properties props = new Properties();
	  //设置为true,则要求以登录方法验证,默认为false
	  props.setProperty("mail.smtp.auth", "true"); 
	  //设置连接服务器的协议
	  props.setProperty("mail.transport.protocol", "smtp");
	  Session session =  Session.getInstance(props);
	  session.setDebug(true);
	  
//创建代表邮件内容的Message对象。
	  Message msg = new MimeMessage(session);
	 //可能是163邮箱特别要求的,Mail from must equal authorized user,所以From必须和登录用户名相同
	  msg.setFrom(new InternetAddress("xh216319@163.com"));
	  msg.setText("this is the first mail by java programing!");
	  msg.setSubject("SendMessageDemo1");

//创建Transport对象、连接服务器、发送Message、关闭连接。 
	  Transport transport = session.getTransport();
	    //设置连接的邮件服务器及其端口以及连接的用户名和密码
	  transport.connect("smtp.163.com", 25, "xh216319","xiaoxiao");
	    /*
	     * Transport.send(Message)与transport.SendMessage(Message)区别
	     * 1.静态类 Transport的send()方法包含三件事:连接服务器、发送邮件、关闭服务器。
	     * 2.实例transport的sendMessage()方法仅仅是发送邮件。
	     * 所以此处不能用Transport.send(Message);
	     * 但是如果是群发邮件的话,最好不要用静态Transport.send(Message),因为其发送一个邮件就会连接一次服务器,这样效率比较低。
	     */
	  transport.sendMessage(msg, new Address[]{new InternetAddress("itstar1965@sina.com")});
	  transport.close();
	   
   }
}

方式2(应用Authenticator类实现用户信息验证):

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 {
//创建包含邮件服务器的网络连接信息的Session对象。
	   Properties props = new Properties();
	   props.setProperty("mail.transport.protocol", "smtp");
	   props.setProperty("mail.host", "smtp.163.com");
	   props.setProperty("mail.smtp.auth", "true");
	   /**
	    * getInstance()和getDefaultInstance()方法的区别:
	    * getInstance()每次调用都会创建一个新Session对象并返回
	    * getDefaultInstance()第一次调用时,会返回一个session对象,并将该session对象设置为缺省值,当第二次调用该方法时,则会返回该缺省session对象
	    **/
	   //因为Authenticator类为抽象类,所以只能以匿名内部类的形式new一个Authenticator的子类对象,并重写其getPasswordAuthentication()方法
       Session session = Session.getInstance(props,
    	   new Authenticator() {
    	     protected PasswordAuthentication getPasswordAuthentication(){
    	    	 return new PasswordAuthentication("xh216319","xiaoxiao");
    	     }
		}
       );
       //设置Debug的方式打印执行过程
       session.setDebug(true);
//创建代表邮件内容的Message对象。
	   Message msg = new MimeMessage(session);
	   msg.setFrom(new InternetAddress("xh216319@163.com"));
	   //使用InternetAddress.parse()方法灵活的将String对象封装为InternetAddress数组
       msg.setRecipients(RecipientType.TO, InternetAddress.parse("itstar1965@sina.com,xh216319@163.com"));
	   msg.setSubject("SendMessageDemo2");
	   msg.setSentDate(new Date(100000));
	   //msg.SetText()是将内容全部全部以文本的形式显示,忽略其中的html标记,而msg.setContent()可以设置将内容以指定格式显示
	   msg.setContent("<span style='color:red'>这是用Authenticator类实现用户信息验证的JavaMail</span>","text/html;charset=utf-8");
//创建Transport对象、连接服务器、发送Message、关闭连接。
	   //这里无需指定发送的Address,其会去Message对象的recipients属性的Address
      Transport.send(msg);
	}

}

session的Environment Properties

Property Description Default Value
mail.store.protocol Specifies the default Message Access Protocol. The Session.getStore() method 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) method. The first appropriate protocol in the config files
mail.transport.protocol Specifies the default Transport Protocol. The Session.getTransport() method returns a Transport object that implements this protocol. The client can override this property and explicitly specify the protocol by using Session.getTransport(String protocol)
method.
The first 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 locate the target host. The local machine
mail.user Specifies the username to provide when 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 overrides the mail.host property. mail.host
mail.protocol.user Specifies the protocol-specific default username for connecting to the Mail server. This overrides the mail.user property. mail.user
mail.from Specifies the return address of the current user. Used by the InternetAddress.getLocalAddress method to specify the current user’s email address. username@host
mail.debug Specifies the initial debug mode. Setting this property to true will turn on debug mode, while setting it to false turns debug mode off. false

Smtp协议相关的环境变量  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.Default is infinite timeout.
mail.smtp.timeout int Socket I/O timeout value in milliseconds. Default is infinite timeout.
mail.smtp.from String Email address to use for SMTP MAIL command. This sets the envelopereturn address. Defaults to msg.getFrom() orInternetAddress.getLocalAddress(). NOTE: mail.smtp.user was previouslyused for this.
mail.smtp.localhost String 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 properly.
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 be set, but useful with multi-homed hostswhere it's important to pick a particular local address 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, do not attempt to sign on with the EHLO command. Defaults totrue. Normally failure of the EHLO command will fallback to the HELOcommand; this property exists only for servers that don't fail EHLOproperly or don't implement EHLO properly.
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 message.See 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 that 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 failure witha SendFailedException. If set to false (the default), the message isnot sent to any of the recipients if there is 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 is sentand the connection is immediately closed.If set to true (the default), causes the transport to waitfor the response to the QUIT command.
mail.smtp.reportsuccess boolean If set to true, causes the transport to include anSMTPAddressSucceededExceptionfor each address that is successful.Note also that this will cause aSendFailedExceptionto
be thrown from thesendMessagemethod ofSMTPTransporteven if all addresses 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 be used to create SMTP sockets.
mail.smtp.socketFactory.fallback boolean If set to true, failure to create a socket using the specifiedsocket factory class will cause the socket to be created usingthejava.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 will 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 well as vendor-specific extensions.Typically the application should use theSMTPTransportmethodsupportsExtensionto
verify that the server supports the desired service extension.SeeRFC 1869and other RFCs that define specific extensions.
mail.smtp.starttls.enable boolean If true, enables the use of the STARTTLS command (ifsupported by the server) to switch the connection to a TLS-protectedconnection before issuing any login commands. Note that an appropriatetrust store must configured so that the client will
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 will 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 will be enabled for SSL connections.The property value is a whitespace separated list of tokens acceptableto thejavax.net.ssl.SSLSocket.setEnabledProtocols method.
mail.smtp.ssl.ciphersuites string Specifies the SSL cipher suites that will be enabled for SSL connections.The property value is a whitespace separated list of tokens acceptableto thejavax.net.ssl.SSLSocket.setEnabledCipherSuites method.

抱歉!评论已关闭.