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 发送邮件的配置信息大全

 

NameTypeDescription
mail.smtp.userStringDefault user name for SMTP.
mail.smtp.hostStringThe SMTP server to connect to.
mail.smtp.portintThe SMTP server port to connect to, if the connect() method doesn't explicitly specify one. Defaults to 25.
mail.smtp.connectiontimeoutintSocket connection timeout value in milliseconds. Default is infinite timeout.
mail.smtp.timeoutintSocket I/O timeout value in milliseconds. Default is infinite timeout.
mail.smtp.fromStringEmail 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.localhostStringLocal 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.localaddressStringLocal 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.localportintLocal port number to bind to when creating the SMTP socket. Defaults to the port number picked by the Socket class.
mail.smtp.ehlobooleanIf 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.authbooleanIf true, attempt to authenticate the user using the AUTH command. Defaults to false.
mail.smtp.auth.mechanismsStringIf 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.submitterStringThe 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.notifyStringThe NOTIFY option to the RCPT command. Either NEVER, or some combination of SUCCESS, FAILURE, and DELAY (separated by commas).
mail.smtp.dsn.retStringThe RET option to the MAIL command. Either FULL or HDRS.
mail.smtp.allow8bitmimebooleanIf 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.sendpartialbooleanIf 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.realmStringThe realm to use with DIGEST-MD5 authentication.
mail.smtp.quitwaitbooleanIf 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.reportsuccessbooleanIf 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.socketFactorySocketFactoryIf 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.classStringIf 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.fallbackbooleanIf 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.portintSpecifies the port to connect to when using the specified socket factory. If not set, the default port will be used.
mail.smtp.ssl.enablebooleanIf 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.checkserveridentitybooleanIf 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.socketFactorySSLSocketFactoryIf 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.classStringIf 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.portintSpecifies the port to connect to when using the specified socket factory. If not set, the default port will be used.
mail.smtp.ssl.protocolsstringSpecifies 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.ciphersuitesstringSpecifies 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.mailextensionStringExtension 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.enablebooleanIf 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.requiredbooleanIf 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.usersetbooleanIf 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为正确的邮件正文了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值