Java Mail(三):Session、Message详解(二)

2014-11-24 03:31:57 · 作者: · 浏览: 1
. abstract void setFrom(Address address)
Set the "From" attribute in this Message. 现在大多数SMTP服务器要求发件人与连接账户必须一致,否则会抛出验证失败的异常,这样是防止用户伪装成其它人的账户恶意发送邮件。

收件人/抄送人/暗送人

void setRecipient(Message.RecipientType type,Address address)
Set the recipient address.
abstract void setRecipients(Message.RecipientType type,Address[] addresses)
Set the recipient addresses.
第一个方法设置单个人,第二个方法设置多个人。方法中第一个参数涉及到另一个类RecipientType,该类是Message的静态内部类,期内有三个常量值:
static Message.RecipientType BCC
The "Bcc" (blind carbon copy) recipients.
static Message.RecipientType CC
The "Cc" (carbon copy) recipients.
static Message.RecipientType TO
The "To" (primary) recipients.
TO - 收件人;CC - 抄送人;BCC - 暗送人。

回复人

void setReplyTo(Address[] addresses)
Set the addresses to which replies should be directed.
设置收件人收到邮件后的回复地址。

标题

abstract void setSubject(String subject)
Set the subject of this message.
设置邮件标题/主题。

内容

void setContent(Multipart mp)
This method sets the given Multipart object as this message's content.
void setContent(Object obj,String type)
A convenience method for setting this part's content.
void setText(String text)
A convenience method that sets the given String as this part's content with a MIME type of "text/plain".
设置邮件文本内容、HTML内容、附件内容。

示例


下面来看一个稍复杂点的示例:
public class JavaMailTest2 {

	public static void main(String[] args) throws MessagingException {
		Properties props = new Properties();
		// 开启debug调试
		props.setProperty("mail.debug", "true");
		// 发送服务器需要身份验证
		props.setProperty("mail.smtp.auth", "true");
		// 设置邮件服务器主机名
		props.setProperty("mail.host", "smtp.163.com");
		// 发送邮件协议名称
		props.setProperty("mail.transport.protocol", "smtp");
		
		// 设置环境信息
		Session session = Session.getInstance(props, new Authenticator() {
			// 在session中设置账户信息,Transport发送邮件时会使用
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("java_mail_001", "javamail");
			}
		});
		
		// 创建邮件对象
		Message msg = new MimeMessage(session);
		// 发件人
		msg.setFrom(new InternetAddress("java_mail_001@163.com"));
		// 多个收件人
		msg.setRecipients(RecipientType.TO, InternetAddress.parse("java_mail_002@163.com,java_mail_003@163.com"));
		// 抄送人
		msg.setRecipient(RecipientType.CC, new InternetAddress("java_mail_001@163.com"));
		// 暗送人
		msg.setRecipient(RecipientType.BCC, new InternetAddress("java_mail_004@163.com"));
		
		// 主题
		msg.setSubject("中文主题");
		// HTML内容
		msg.setContent("
  
你好啊
", "text/html;charset=utf-8"); // 连接邮件服务器、发送邮件、关闭连接,全干了 Transport.send(msg); } }
本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/17909093,转载请注明。