很久没来更新了,这次是关于发送邮件和附件的。
import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendEmail


{
private static String host = ""; // SMTP服务器地址

private static String user = ""; // 用户名

private static String password = ""; // 密码

private static String from = ""; // 发件人

private static String to = ""; // 收件人

/** *//**
*
* @param subject 邮件主题
* @param content 邮件内容
* @param filename 附件
*/
public static void send(String subject, String content, String filename)

{
Properties props = new Properties();
BodyPart bp = new MimeBodyPart();
Multipart mp = new MimeMultipart();
props.put("mail.smtp.host", host);//指定SMTP服务器
props.put("mail.transpost.protocol", "smtp");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");//指定是否需要SMTP验证
try

{
Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台显示debug信息

Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));//发件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));//收件人
//message.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(to));//抄送
message.setSubject(subject);//邮件主题
//message.setContent(content);//邮件正文无需附件时可以使用
bp.setContent(content, "text/html;charset=GB2312");//邮件正文
mp.addBodyPart(bp);
// 附件
if (!StringUtil.isBlank(filename))

{
File file = new File(filename);
if (file.exists())

{
BodyPart mdp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(file);
mdp.setDataHandler(new DataHandler(fileds));
mdp.setFileName(fileds.getName());
mp.addBodyPart(mdp);
}
}
message.setContent(mp);
message.saveChanges();

Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (Exception e)

{
System.out.println(e);
return;
}
}

public static void main(String[] args)

{
SendEmail.send("测试邮件", "这个是测试内容!", "D:\\update.xls");
}
}

posted on 2010-11-15 17:17
Jarry 阅读(176)
评论(0) 编辑 收藏