处理HTML消息
发送基于HTML的消息比发送纯文本消息要稍微复杂一点,尽管它不需要做大量的工作。它全部取决于您特定的需求。
发送HTML消息
如果您所要做的全部工作是发送一个等价的HTML文件作为消息,并让邮件阅读者忧心于取出任何嵌入的图片或相关片段,那么就可以使用消息的setContent()方法,以字符串形式传递消息内容,并把内容类型设置为text/html。
- String htmlText = "
Hello
" + - "<img src=\"http://www.jguru.com/images/logo.gif\">";
- message.setContent(htmlText, "text/html"));
在接收端,如果您用JavaMail API获取消息,在该API中没有内置任何用于以HTML格式显示消息的功能。JavaMail API只以字节流的形式来查看消息。要以HTML格式显示消息,您必须使用Swing JeditorPane或某些第3方HTML阅读器组件。
- if (message.getContentType().equals("text/html")) {
- String content = (String)message.getContent();
- JFrame frame = new JFrame();
- JEditorPane text = new JEditorPane("text/html", content);
- text.setEditable(false);
- JScrollPane pane = new JScrollPane(text);
- frame.getContentPane().add(pane);
- frame.setSize(300, 300);
- frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
- frame.show();
- }
在消息中包含图片
另一方面,如果您的HTML消息中嵌入了作为消息一部分的图片,并且您想保持消息内容的完整,就必须把图片看作附件,并用特殊的通信标识符URL引用该图片,该通信标识符引用的是图片附件的内容ID报文。
嵌入图片的处理与附加一个文件到消息上非常相似,惟一的不同之处在于:您必须区分MimeMultipart中,哪些部分是在构造器(或通过setSubType()方法)通过设置其子类型而使之相关的,以及将图片的内容ID报头设置成任意字符串,它将在img标记中用作图片的源路径。下面显示了一个完整的示例:
- String file = ...;
- // Create the message
- Message message = new MimeMessage(session);
- // Fill its headers
- message.setSubject("Embedded Image");
- message.setFrom(new InternetAddress(from));
- message.addRecipient(Message.RecipientType.TO,
- new InternetAddress(to));
- // Create your new message part
- BodyPart messageBodyPart = new MimeBodyPart();
- String htmlText = "<H1>Hello</H1>" +
- "<img src=\"cid:memememe\">";
- messageBodyPart.setContent(htmlText, "text/html");
- // Create a related multi-part to combine the parts
- MimeMultipart multipart = new MimeMultipart("related");
- multipart.addBodyPart(messageBodyPart);
- // Create part for the image
- messageBodyPart = new MimeBodyPart();
- // Fetch the image and associate to part
- DataSource fds = new FileDataSource(file);
- messageBodyPart.setDataHandler(new DataHandler(fds));
- messageBodyPart.setHeader("Content-ID","memememe");
- // Add part to multi-part
- multipart.addBodyPart(messageBodyPart);
- // Associate multi-part with message
- message.setContent(multipart);
练习
发送带有图片的 HTML 消息
用SearchTerm搜索
JavaMail API包含一种可用于创建SearchTerm(搜索条件)的筛选机制,它可以在javax.mail.search包中找到。一旦创建了SearchTerm,您就可以询问某个文件夹匹配的消息,并检索出消息对象数组:
- SearchTerm st = ...;
- Message[] msgs = folder.search(st);
有22种不同的类可用于帮助创建搜索条件。
· AND条件(AndTerm类)
· OR条件(OrTerm类)
· NOT条件(NotTerm类)
· SENT DATE条件(SentDateTerm类)
· CONTENT条件(BodyTerm类)
· HEADER条件(FromTerm / FromStringTerm, RecipientTerm / RecipientStringTerm, SubjectTerm, etc.)
本质上,您可以为匹配的消息创建一个逻辑表达式,然后进行搜索。例如,下面显示了一条消息的条件搜索示例,该消息带有(部分带有)一个ADV主题字符串,其发送者字段为friend@public.com。您可能考虑定期运行该查询,并自动删除任何返回的消息。
- SearchTerm st =
- new OrTerm(
- new SubjectTerm("ADV:"),
- new FromStringTerm("friend@public.com"));
- Message[] msgs = folder.search(st);
一个支持多附件的mail发送类
package mail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.activation.*;
import java.io.*;
/**
*
Title:
*
Description:
*
Copyright: Copyright (c) 2004
*
Company:
* @author 黄新
* @version 1.0
*/
public class Mail {
public Mail() {
}
/**
* 发送邮件
* @param to 收件人
* @param subject 主题
* @param body 主体 邮件内容
* @param from 法件人
* @param PassWord 密码
* @param str_files 附件 数组
* @return 是否发送成功 只能以是否跑出异常来做判断 寻求更好的判断方法
*/
public boolean sendMail(String to,String subject,String body, String from,String PassWord,String []str_files){
Properties props = new Properties();
boolean isSended = true;
try {
String protocol = "smtp";//smtp pop3
String host = getHost(from,protocol);
String username = getUsername(from);
//Setup mail server
props.put("mail."+protocol+".host",host);//smtp pop3
//Get Session
props.put("mail."+protocol+".auth","true");
PopupAuthenticator popAuthenticator = new PopupAuthenticator();
PasswordAuthentication pop = popAuthenticator.performCheck(username,PassWord);
Session session = Session.getInstance(props,popAuthenticator);
//Define message
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setSentDate(new java.util.Date ()) ;
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject(subject);
//给消息对象设置内容
BodyPart textBodyPart=new MimeBodyPart();
textBodyPart.setContent(body,"text/html;charset=gb2312") ;
Multipart mm=new MimeMultipart();
mm.addBodyPart(textBodyPart);
int i = str_files.length ;
mm.addBodyPart(getFileBodyPart(str_files[i-1])) ;
i--;
}
message.setContent(mm) ;
message.saveChanges() ;
Transport.send(message);
}
catch(AuthenticationFailedException afe){
isSended = false;
System.out.println("登陆验证出现错误 ,请检查你的用户名和密码") ;
afe.printStackTrace() ;
}
catch(MessagingException me){
isSended = false;
me.printStackTrace() ;
System.out.print("") ;
}
catch(Exception e){
isSended = false;
e.printStackTrace() ;
}
return isSended;
}
/**
* 获得通过邮件地址获取用户名
* @param email 邮件地址
* @return 用户名
*/
private String getUsername(String email){
StringBuffer str = new StringBuffer(email);
String usename = str.substring(0,str.indexOf("@") ) ;
return usename;
}
/**
* 通过邮件地址获取邮件服务器地址
* @param email 邮件地址
* @param protocol 邮件协议
* @return 邮件服务器主机地址
*/
private String getHost(String email,String protocol){
StringBuffer str = new StringBuffer(email);
String host = protocol+"." + str.substring(str.indexOf("@")+1 ) ;
return host;
}
private BodyPart getFileBodyPart(String str_file){
BodyPart fileBodyPart = new MimeBodyPart();
// int NO_files = str_files.length ;
try {
File file = new File(str_file);
FileDataSource fds=new FileDataSource(file);//用本地文件
DataHandler dh = new DataHandler(fds);
fileBodyPart.setFileName(file.getName());//可以和原文件名不一致
fileBodyPart.setDataHandler(dh);
}
catch (MessagingException ME) {
ME.printStackTrace() ;
System.out.println("获取文件名setFileName或设置setDataHandler时出现错误") ;
return null;
}
return fileBodyPart;
}
public static void main(String[] args) {
String[] str_files ={"G:\\192.168.7.144备份\\学习资料\\技术文章\\eclipse 参考手册\\CSDN_eclipse 参考手册(三).htm ","G:\\日立.html"};
Mail m = new Mail();
System.out.println(m.sendMail("xini_huang@hotmail.com","nihao","helloworld!!!!","huangxinyi2003@163.com","差点把自己的密码给泄漏了",str_files)) ;
//System.out.println(m.getUsername("huangxinyi2003@163.com")+"======"+m.getHost("huangxinyi2003@163.com") ) ;
}
}
[ Last edited by 黄新 on 2004-12-2 at 16:31 ]
2004-12-2 16:26
黄新
积分 293
发贴 263
注册 2003-6-22
来自 福建漳州
状态 离线 验证
package mail;
import javax.mail.*;
import javax.mail.internet.*;
/**
*
Title:
*
Description:
*
Copyright: Copyright (c) 2004
*
Company:
* @author 黄新
* @version 1.0
*/
public class PopupAuthenticator extends Authenticator{
String username=null;
String password=null;
public PopupAuthenticator(){
}
public PasswordAuthentication performCheck(String user,String pass){
username = user;
password = pass;
return getPasswordAuthentication();
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
public static void main(String[] args) {
}
}