JavaMail 杂记

我们在收取邮件的时候,经常邮件工具会提醒:邮件发送者要求回执,是否发送阅读回执之类的信息。

在使用 JavaMail 发送邮件时,我们可以通过下面的设置来要求邮件接收者给我们发送回执。

1. 直接调用 MimeMessage 对象的 setHeader 方法

MimeMessage msg = ....
msg.setHeader("Disposition-Notification-To","1");

2. 使用 Commons-Email 进行发送时

HtmlEmail body = new HtmlEmail();
body.addHeader("Disposition-Notification-To", "1");

即可。

JavaMail 发送邮件的配置信息大全

 

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't explicitly 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 envelope return address. Defaults to msg.getFrom() or InternetAddress.getLocalAddress(). NOTE: mail.smtp.user was previously used 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 to be 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 hosts where 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 to true. Normally failure of the EHLO command will fallback to the HELO command; this property exists only for servers that don't fail EHLO properly 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.auth.mechanisms String If set, lists the authentication mechanisms to consider, and the order in which to consider them. Only mechanisms supported by the server and supported by the current implementation will be used. The default is "LOGIN PLAIN DIGEST-MD5", which includes all the authentication mechanisms supported by the current implementation.
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 the original submitter of the message. See also the setSubmitter method of SMTPMessage. Mail clients typically do not use this.
mail.smtp.dsn.notify String The NOTIFY option to the RCPT command. Either NEVER, or some combination 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, text parts of messages that use the "quoted-printable" or "base64" encodings are converted to use "8bit" encoding if they follow the RFC2045 rules for 8bit text.
mail.smtp.sendpartial boolean If set to true, and a message has some valid and some invalid addresses, send the message anyway, reporting the partial failure with a SendFailedException. If set to false (the default), the message is not sent to any of the recipients if there is an invalid recipient address.
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 sent and the connection is immediately closed. If set to true (the default), causes the transport to wait for the response to the QUIT command.
mail.smtp.reportsuccess boolean If set to true, causes the transport to include an SMTPAddressSucceededException for each address that is successful. Note also that this will cause a SendFailedException to be thrown from the sendMessage method of SMTPTransport even if all addresses were correct and the message was sent successfully.
mail.smtp.socketFactory SocketFactory If set to a class that implements the javax.net.SocketFactory interface, this class will be used to create SMTP sockets. Note that this is an instance of a class, not a name, and must be set using the put method, not the setProperty method.
mail.smtp.socketFactory.class String If set, specifies the name of a class that implements the javax.net.SocketFactory interface. This class will be used to create SMTP sockets.
mail.smtp.socketFactory.fallback boolean If set to true, failure to create a socket using the specified socket factory class will cause the socket to be created using the java.net.Socket class. Defaults to true.
mail.smtp.socketFactory.port int Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used.
mail.smtp.ssl.enable boolean If set to true, use SSL to connect and use the SSL port by default. Defaults to false for the "smtp" protocol and true for the "smtps" protocol.
mail.smtp.ssl.checkserveridentity boolean If set to true, check the server identity as specified by RFC 2595. These additional checks based on the content of the server's certificate are intended to prevent man-in-the-middle attacks. Defaults to false.
mail.smtp.ssl.socketFactory SSLSocketFactory If set to a class that extends the javax.net.ssl.SSLSocketFactory class, this class will be used to create SMTP SSL sockets. Note that this is an instance of a class, not a name, and must be set using the put method, not the setProperty method.
mail.smtp.ssl.socketFactory.class String If set, specifies the name of a class that extends the javax.net.ssl.SSLSocketFactory class. This class will be used to create SMTP SSL sockets.
mail.smtp.ssl.socketFactory.port int Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used.
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 acceptable to the javax.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 acceptable to the javax.net.ssl.SSLSocket.setEnabledCipherSuites method.
mail.smtp.mailextension String Extension string to append to the MAIL command. The extension string can be used to specify standard SMTP service extensions as well as vendor-specific extensions. Typically the application should use the SMTPTransport method supportsExtension to verify that the server supports the desired service extension. See RFC 1869 and other RFCs that define specific extensions.
mail.smtp.starttls.enable boolean If true, enables the use of the STARTTLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any login commands. Note that an appropriate trust store must configured so that the client will trust the server's certificate. Defaults to false.
mail.smtp.starttls.required boolean If true, requires the use of the STARTTLS command. If the server doesn't support the STARTTLS command, or the command fails, the connect method will fail. Defaults to false.
mail.smtp.userset boolean If set to true, use the RSET command instead of the NOOP command in the isConnected method. In some cases sendmail will respond slowly after many NOOP commands; use of RSET avoids this sendmail issue. Defaults to false.
JavaMail邮件别名和主题乱码解决

编码

邮件头

邮件头(参见RFC822RFC2047)只能包含US-ASCII字符。邮件头中任何包含非US-ASCII字符的部分必须进行编码,使其只包含US-ASCII字符。所以使用java mail发送中文邮件必须经过编码,否则别人收到你的邮件只能是乱码一堆。不过使用java mail 包的解决方法很简单,用它自带的MimeUtility工具中encode开头的方法(如encodeText)对中文信息进行编码就可以了。

        例子:

         MimeMessage mimeMsg = new MimeMessage(mailSession);

// javamail决定用什么方式来编码 ,编码内容的字符集是系统字符集

mimeMsg.setSubject( MimeUtility.encodeText( Subject) );

// 使用指定的base64方式编码,并指定编码内容的字符集是gb2312

mimeMsg.setSubject( MimeUtility.encodeText( Subject,”gb2312”,”B”)); //Bbase64方式

 

        

通常对邮件头的编码方式有2,一种是base64方式编码,一种是QPquoted-printable)方式编码,javamail根据具体情况来选择编码方式。

         如“txt测试”编码后内容如下:

=?GBK?Q?Txt=B2=E2=CA=D4

         里面有个=?GBK?Q?GBK表示的是内容的字符集,?Q?表示的是以QP方式编码的(?B?则是以base64方式编码),后面紧跟的才是编码后的中文字符。所以用MimeUtility工具编码后的信息里包含了编码方式的信息。

 

邮件正文

邮件的正文也要进行编码,但它不能用MimeUtility里的方法来编码。邮件正文的编码方式的信息是要放在Content-Transfer-Encoding这个邮件头参数中的,而MimeUtility里面的方法是将编码方式的信息放在编码后的正文内容中。所以如果你对正文也用MimeUtility进行处理,那么其他邮件程序就不会正常显示你编码的邮件,因为其他邮件软件如outlook,foxmail只会根据Content-Transfer-Encoding这个里面的信息来对邮件正文进行解码。

其实,邮件正文部分的编码javamail已经自动帮你做了,当你发送邮件的时候,它会自己决定编码方式,并把编码方式的信息放入Content-Transfer-Encoding这个邮件头参数中,然后再发送。所以你所要做的就是直接把邮件正文的内容放入邮件中就可以了。

对邮件正文的编码方式比较多,包括了base64QP方式,还有一些如7bit,8bit等等,因为javamail自动为邮件正文编码,所以我就不一一祥叙了。

例子:

// 处理邮件正文

MimeBodyPart mbp=new MimeBodyPart();

if ( ContentType == null || ContentType.equals("")) // ContentType为编码类型,如GBK

mbp.setText( Content ); // JavaMail来决定编码

else

mbp.setContent( Content, ContentType); // 指定编码格式

 

解码

邮件头javamail包中的MimeUtility工具中也提供了对邮件信息解码的方法,都是以decode开头的一些方法(decodeText)

 

例子:

String Subject = mimemsg.getSubject();

String ChSubject = MimeUtility.decodeText(Subject);

 

对于base64QP编码后信息,decode* 方法能将他们正确的解码,但是,如果指定的字符集不对,那么javamail就会出现错误,不能正确地将其解码。

如有的邮件系统将”txt测试”编码后如下:

=?x-unkown?Q?Txt=B2=E2=CA=D4

这里指定的字符集是x-unknown,是非明确的字符集,javamail就不能正确的处理了,但是”测试”这两个中文字还是按照gbk字符集编码的,所以你可以手工的将编码方式信息改正确,再用decode*方法来解码。

例子:

if ( str.indexOf("=?x-unknown?") >=0 ){

str = str.replaceAll("x-unknown","gbk"); // 将编码方式的信息由x-unkown改为gbk

try{

str = MimeUtility.decodeText( str ); //再重新解码

} catch( Exception e1){

return str ;

}

         }

 

         邮件正文decode*方法都是根据在编码信息中包含的编码方式的信息来解码,所以decode*方法对邮件正文解码是无效的,因为邮件正文中不包含编码方式的信息。

同编码一样,邮件正文的解码也是由javamail做了。Javamail根据Content-Transfer-Encoding里的信息,来对邮件的正文解码。

客户程序从javamail取得的正文内容字符集为iso-8859-1,所以还要将字符集转换一下。

例子:

String CorrectContent = new String( Content.getbytes(“iso-8859-1”),”gb2312”);

CorrentContent为正确的邮件正文了

你可能感兴趣的:(jdk,.net,socket,软件测试)