发送带有附件的邮件 发送带有附件的邮件的过程有些类似转发邮件,我们需要建立一个完整邮件的各个邮件体部分,在第一个部分(即我们的邮件内容文字)后,增加一个具有DataHandler的附件而不是在转发邮件时那样复制第一个部分的DataHandler。如果我们将文件作为附件发送,那么要建立FileDataSource类型的对象作为附件数据源;如果从URL读取数据作为附件发送,那么将要建立URLDataSource类型的对象作为附件数据源。然后将这个数据源(FileDataSource或是URLDataSource)对象作为DataHandler类构造方法的参数传入,从而建立一个DataHandler对象作为数据源的DataHandler。接着将这个DataHandler设置为邮件体部分的DataHandler。这样就完成了邮件体与附件之间的关联工作,下面的工作就是BodyPart的setFileName()方法设置附件名为原文件名。最后将两个邮件体放入到Multipart中,设置邮件内容为这个容器Multipart,发送邮件。 // Define messageMessage message = new MimeMessage(session);message.setFrom(new InternetAddress(from));message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));message.setSubject("Hello JavaMail Attachment");// Create the message part BodyPart messageBodyPart = new MimeBodyPart();// Fill the messagemessageBodyPart.setText("Pardon Ideas");Multipart multipart = new MimeMultipart();multipart.addBodyPart(messageBodyPart);// Part two is attachmentmessageBodyPart = new MimeBodyPart();DataSource source = new FileDataSource(filename);messageBodyPart.setDataHandler(new DataHandler(source));messageBodyPart.setFileName(filename);multipart.addBodyPart(messageBodyPart);// Put parts in messagemessage.setContent(multipart);// Send the messageTransport.send(message);如果我们使用servlet实现发送带有附件的邮件,则必须上传附件给servlet,这时需要注意提交页面form中对编码类型的设置应为multipart/form-data。
session = Session.getInstance(new Properties(), new MailAuthenticator(username, password)); folder = session.getFolder(server);
System.out.println("\n\n\nFolder retrieved for " + serverString + ", with " + folder.getMessageCount() + " messages");
return folder; } public static void getEmailWithSubjectContaining(String emailUrl, String username, String password, String regex, String filepath, boolean addPrefix, boolean delete) throws Exception { Folder folder = getMailFolder(emailUrl, username, password); if (folder == null) return; folder.open(Folder.READ_WRITE); Message[] msgs = folder.getMessages(); System.out.println("Totally there are " + msgs.length); for (int i = 0; i < msgs.length; i++) { String pathToSave = filepath;
String subject = msgs[i].getSubject(); System.out.println("Email subject: " + subject); if (!subject.matches(regex)) { System.out.println("Email subject doesn't match regex: " + regex + ", this email is ignored."); continue; } Part p = (Part) msgs[i]; if (addPrefix) { pathToSave = pathToSave + "/" + getFilenamePrefix(subject); } dumpAttachment(p, pathToSave); msgs[i].setFlag(Flags.Flag.DELETED, delete); //得到邮件后删除 } folder.expunge(); //清除邮箱里DELETE的邮件 folder.close(false); } public static void dumpAttachment(Part part, String filepath) throws Exception{ if (part.isMimeType("text/plain")) { System.out.println("This is plain text"); } else if (part.isMimeType("multipart/*")) { System.out.println("This is a Multipart, trying to dig into the attachment now"); Multipart mp = (Multipart) part.getContent(); int count = mp.getCount(); for (int i = 0; i < count; i++) dumpAttachment(mp.getBodyPart(i), filepath); } else if (part.isMimeType("message/rfc822")) { System.out.println("This is a Nested Message"); dumpAttachment((Part) part.getContent(), filepath); } else { Object o = part.getContent(); String attachmentFilename = "no_name"; if (part.getFileName() != null && !part.getFileName().equals("")) { attachmentFilename = part.getFileName(); }
if (o instanceof String) { System.out.println("This is a string"); } else if (o instanceof InputStream) { System.out.println("This is just an input stream"); InputStream is = (InputStream) o;
FileOutputStream fos = new FileOutputStream(filepath + formatFileExtension(attachmentFilename)); int c; int count = 0; System.out.print("Saving attachment: " + formatFileExtension(attachmentFilename)); while ((c = is.read()) != -1) { fos.write(c); if (count % 1000000 == 0) { System.out.print("\n"); } else if (count % 5000 == 0) { System.out.print("."); }
发送带有附件的邮件的过程有些类似转发邮件,我们需要建立一个完整邮件的各个邮件体部分,在第一个部分(即我们的邮件内容文字)后,增加一个具有DataHandler的附件而不是在转发邮件时那样复制第一个部分的DataHandler。如果我们将文件作为附件发送,那么要建立FileDataSource类型的对象作为附件数据源;如果从URL读取数据作为附件发送,那么将要建立URLDataSource类型的对象作为附件数据源。然后将这个数据源(FileDataSource或是URLDataSource)对象作为DataHandler类构造方法的参数传入,从而建立一个DataHandler对象作为数据源的DataHandler。接着将这个DataHandler设置为邮件体部分的DataHandler。这样就完成了邮件体与附件之间的关联工作,下面的工作就是BodyPart的setFileName()方法设置附件名为原文件名。最后将两个邮件体放入到Multipart中,设置邮件内容为这个容器Multipart,发送邮件。
// Define messageMessage message = new MimeMessage(session);message.setFrom(new InternetAddress(from));message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));message.setSubject("Hello JavaMail Attachment");// Create the message part BodyPart messageBodyPart = new MimeBodyPart();// Fill the messagemessageBodyPart.setText("Pardon Ideas");Multipart multipart = new MimeMultipart();multipart.addBodyPart(messageBodyPart);// Part two is attachmentmessageBodyPart = new MimeBodyPart();DataSource source = new FileDataSource(filename);messageBodyPart.setDataHandler(new DataHandler(source));messageBodyPart.setFileName(filename);multipart.addBodyPart(messageBodyPart);// Put parts in messagemessage.setContent(multipart);// Send the messageTransport.send(message);如果我们使用servlet实现发送带有附件的邮件,则必须上传附件给servlet,这时需要注意提交页面form中对编码类型的设置应为multipart/form-data。
import javax.mail.Authenticator;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.URLName;......
public static Folder getMailFolder(String serverString, String username, String password) throws Exception {
Folder folder = null;
URLName server = new URLName(serverString);
session = Session.getInstance(new Properties(),
new MailAuthenticator(username, password)); folder = session.getFolder(server);
System.out.println("\n\n\nFolder retrieved for " + serverString + ", with " + folder.getMessageCount() + " messages");
return folder;
} public static void getEmailWithSubjectContaining(String emailUrl,
String username, String password, String regex, String filepath,
boolean addPrefix, boolean delete) throws Exception {
Folder folder = getMailFolder(emailUrl, username, password); if (folder == null)
return; folder.open(Folder.READ_WRITE); Message[] msgs = folder.getMessages(); System.out.println("Totally there are " + msgs.length);
for (int i = 0; i < msgs.length; i++) {
String pathToSave = filepath;
String subject = msgs[i].getSubject(); System.out.println("Email subject: " + subject); if (!subject.matches(regex)) {
System.out.println("Email subject doesn't match regex: " + regex + ", this email is ignored.");
continue;
} Part p = (Part) msgs[i]; if (addPrefix) {
pathToSave = pathToSave + "/" + getFilenamePrefix(subject);
} dumpAttachment(p, pathToSave); msgs[i].setFlag(Flags.Flag.DELETED, delete); //得到邮件后删除
} folder.expunge(); //清除邮箱里DELETE的邮件
folder.close(false);
} public static void dumpAttachment(Part part, String filepath) throws Exception{
if (part.isMimeType("text/plain")) {
System.out.println("This is plain text");
} else if (part.isMimeType("multipart/*")) {
System.out.println("This is a Multipart, trying to dig into the attachment now");
Multipart mp = (Multipart) part.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++)
dumpAttachment(mp.getBodyPart(i), filepath);
} else if (part.isMimeType("message/rfc822")) {
System.out.println("This is a Nested Message");
dumpAttachment((Part) part.getContent(), filepath);
} else {
Object o = part.getContent();
String attachmentFilename = "no_name";
if (part.getFileName() != null && !part.getFileName().equals("")) {
attachmentFilename = part.getFileName();
}
if (o instanceof String) {
System.out.println("This is a string");
} else if (o instanceof InputStream) {
System.out.println("This is just an input stream");
InputStream is = (InputStream) o;
FileOutputStream fos = new FileOutputStream(filepath + formatFileExtension(attachmentFilename));
int c;
int count = 0;
System.out.print("Saving attachment: " + formatFileExtension(attachmentFilename));
while ((c = is.read()) != -1) {
fos.write(c);
if (count % 1000000 == 0) {
System.out.print("\n");
} else if (count % 5000 == 0) {
System.out.print(".");
}
count ++;
} System.out.println("\nAttachment " + (format.format((double)count/1024)) + " Kilobytes saved as '" + filepath + formatFileExtension(attachmentFilename) + "'\n");
} else {
System.out.println("This is an unknown type");
System.out.println(o.toString());
}
}
}
......
package com.me.util.mail;/**
* @author Zhangkun [email protected]
* @version 1.0
*/import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import javax.activation.*;
import java.io.*;
import com.me.util.*;public class sendMail { private MimeMessage mimeMsg; //MIME邮件对象 private Session session; //邮件会话对象
private Properties props; //系统属性
private boolean needAuth = false; //smtp是否需要认证 private String username = ""; //smtp认证用户名和密码
private String password = ""; private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象 /**
*
*/
public sendMail() {
setSmtpHost(getConfig.mailHost);//如果没有指定邮件服务器,就从getConfig类中获取
createMimeMessage();
} public sendMail(String smtp){
setSmtpHost(smtp);
createMimeMessage();
} /**
* @param hostName String
*/
public void setSmtpHost(String hostName) {
System.out.println("设置系统属性:mail.smtp.host = "+hostName);
if(props == null)props = System.getProperties(); //获得系统属性对象 props.put("mail.smtp.host",hostName); //设置SMTP主机
}
/**
* @return boolean
*/
public boolean createMimeMessage()
{
try{
System.out.println("准备获取邮件会话对象!";
session = Session.getDefaultInstance(props,null); //获得邮件会话对象
}
catch(Exception e){
System.err.println("获取邮件会话对象时发生错误!"+e);
return false;
} System.out.println("准备创建MIME邮件对象!";
try{
mimeMsg = new MimeMessage(session); //创建MIME邮件对象
mp = new MimeMultipart(); return true;
}
catch(Exception e){
System.err.println("创建MIME邮件对象失败!"+e);
return false;
}
} /**
* @param need boolean
*/
public void setNeedAuth(boolean need) {
System.out.println("设置smtp身份认证:mail.smtp.auth = "+need);
if(props == null)props = System.getProperties(); if(need){
props.put("mail.smtp.auth","true";
}else{
props.put("mail.smtp.auth","false";
}
} /**
* @param name String
* @param pass String
*/
public void setNamePass(String name,String pass) {
username = name;
password = pass;
}
/**
* @param mailSubject String
* @return boolean
*/
public boolean setSubject(String mailSubject) {
System.out.println("设置邮件主题!";
try{
mimeMsg.setSubject(mailSubject);
return true;
}
catch(Exception e) {
System.err.println("设置邮件主题发生错误!";
return false;
}
}
/**
* @param mailBody String
*/
public boolean setBody(String mailBody) {
try{
BodyPart bp = new MimeBodyPart();
bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+mailBody,"text/html;charset=GB2312";
mp.addBodyPart(bp); return true;
}
catch(Exception e){
System.err.println("设置邮件正文时发生错误!"+e);
return false;
}
}
/**
* @param name String
* @param pass String
*/
public boolean addFileAffix(String filename) { System.out.println("增加邮件附件:"+filename); try{
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName()); mp.addBodyPart(bp); return true;
}
catch(Exception e){
System.err.println("增加邮件附件:"+filename+"发生错误!"+e);
return false;
}
} /**
* @param name String
* @param pass String
*/
public boolean setFrom(String from) {
System.out.println("设置发信人!";
try{
mimeMsg.setFrom(new InternetAddress(from)); //设置发信人
return true;
}
catch(Exception e)
{ return false; }
}
/**
* @param name String
* @param pass String
*/
public boolean setTo(String to){
if(to == null)return false; try{
mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
return true;
}
catch(Exception e)
{ return false; } } /**
* @param name String
* @param pass String
*/
public boolean setCopyTo(String copyto)
{
if(copyto == null)return false;
try{
mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
return true;
}
catch(Exception e)
{ return false; }
}
/**
* @param name String
* @param pass String
*/
public boolean sendout()
{
try{
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println("正在发送邮件...."; Session mailSession = Session.getInstance(props,null);
Transport transport = mailSession.getTransport("smtp";
transport.connect((String)props.get("mail.smtp.host",username,password);
transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
//transport.send(mimeMsg); System.out.println("发送邮件成功!";
transport.close(); return true;
}
catch(Exception e)
{
System.err.println("邮件发送失败!"+e);
return false;
}
}
/**
* Just do it as this
*/
public static void main(String[] args) { String mailbody = "<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+
"<div align=center><a href=http://www.csdn.net> csdn </a></div>"; sendMail themail = new sendMail("smtp.msn.com";
themail.setNeedAuth(true); if(themail.setSubject("标题" == false) return;
if(themail.setBody(mailbody) == false) return;
if(themail.setTo("[email protected]" == false) return;
if(themail.setFrom("[email protected]" == false) return;
if(themail.addFileAffix("c:\\boot.ini" == false) return;
themail.setNamePass("user","password"; if(themail.sendout() == false) return;
}
}