图2 从SimpleSender读取的消息
SimpleSender类主要由Send(…)方法完成。其代码如下:
/**
* "send" method to send the message.
*/
public static void send(String smtpServer, String to, String from
, String subject, String body)
{
try
{
Properties props = System.getProperties();
// -- Attaching to default Session, or we could start a new one --
props.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(props, null);
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to, false));
// -- We could include CC recipients too --
// if (cc != null)
// msg.setRecipients(Message.RecipientType.CC
// ,InternetAddress.parse(cc, false));
// -- Set the subject and body text --
msg.setSubject(subject);
msg.setText(body);
// -- Set some other header information --
msg.setHeader("X-Mailer", "LOTONtechEmail");
msg.setSentDate(new Date());
// -- Send the message --
Transport.send(msg);
System.out.println("Message sent OK.");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
首先,请注意,你得到一个emailsession(java.mail.Session),没有它你什么都做不了。在这个案例中,你调用了Sesion.getDefultInstance(…)来得到一个共享session,其它的桌面应用程序也可以使用它;你也可以通过Session.getInstance(…)方法建立一个新的session,它对于你的应用程序来说是唯一的。然后我们能够证明email客户端应用程序对每个用户来说,其使用方法都是一样的,比如它可以是一个用servlet实现的基于Web的email系统。
建立一个session需要设置一些属性;如果你通过SMTP发送消息,那么至少需要设置mail.smtp.host属性。在API文档中你可以找到其它的属性。
现在你有了一个session,创建了一个消息。在这个例子中,你就可以设置email地址信息、主题、正文了,所有这些都取自于命令行。你也可以设置一些头信息,包括日期等,并且你还可以指定复制(CC)的收件人。
最后,你通过javax.mail.Transport类发送消息。如果你想知道我们的emailsession,请看后面的消息构造器。
不仅仅可以发送普通文本
javax.mail.Message(继承javax.mail.Part接口)类中的setText(…)方法把消息内容赋给所提供的字符串,把MIME设置为text/plain。
但是,你不仅仅可以发送普通文本,你还可以通过setDateHandler(…)方法发送其它类型的内容。在大多数情况下,你能通过采用“其它类型内容”来指定文件附件,比如Word文档,但是有趣的是,你检查这里的代码发现它发送一个Java序列化的对象:
ByteArrayOutputStream byteStream=new ByteArrayOutputStream();
ObjectOutputStream objectStream=new ObjectOutputStream(byteStream);
objectStream.writeObject(theObject);
msg.setDataHandler(new DataHandler( new ByteArrayDataSource( byteStream.toByteArray(), "lotontech/javaobject" )));
在javax.mail.*包结构中你可能找不到DataHandler类,因为它属于JavaBeans Activation Framework (JAF)的javax.activation包。JAF提供处理数据内容类型的机制,这种机制主要是针对Internet内容而言,也即MIME类型。
假如你已经试验过了以上的代码,通过email来发送一个Java对象,你可能碰到定位ByteArrayDataSource类的问题,因为要么是mail.jar要么是activation.jar未被包含在程序里面。可以到JavaMail demo目录下去查找一下。
至于你一开始就感兴趣的附件,你可以在DataHandler的构造器中建立一个javax.activation.FileDataSource实例来实现。当然,你不可能单独发送一个文件;它可以作为一个文本消息的附件发送。可能你需要理解多部分消息的概念,现在,我在接收email的环境下为你介绍这个概念。