/** * 使用smtp发送邮件 主程序 * @throws MessagingException mail发送失败 */ public void smtp(String content) throws MessagingException { if (smtpHost == null) throw new MessagingException("smtpHost not found"); if (user == null) throw new MessagingException("user not found"); if (password == null) throw new MessagingException("password not found");
Properties properties = new Properties(); properties.put("mail.smtp.host",smtpHost);//设置smtp主机 properties.put("mail.smtp.auth", "true");//使用smtp身份验证 Session session = Session.getInstance(properties, new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } });
//获得邮件会话对象 MimeMessage mimeMsg = new MimeMessage(session);//创建MIME邮件对象 if (sender != null)//设置发件人地址 { mimeMsg.setFrom(new InternetAddress(sender)); } if (receiver != null)//设置收件人地址 { mimeMsg.setRecipients(Message.RecipientType.TO, parse(receiver)); } if (subject != null)//设置邮件主题 { mimeMsg.setSubject(subject, "GBK"); } MimeBodyPart part = new MimeBodyPart();//mail内容部分 part.setText(content == null ? "" : content, "GBK");
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;class ExtendString {
public ExtendString() {
}
/**
去掉字符串两端的空白字符,并将字符串转化为中国的标准字符gb2312的字符串.
*/
public String CS(String str) { //去掉字符串2端的空白字符
try {
if (str == null)
return "";
str = str.trim();
if (str == null)
return "";
str = new String(str.getBytes("8859_1"), "GBK");
} catch (Exception e) {
System.out.println(e);
}
return str;
}
}public class TestMail {
private String errMsg = "";
private ExtendString ExStr = new ExtendString();
private String sender = "";//发件人地址
private String receiver = "";//收件人地址
private String smtpHost = "";//邮件发送服务器(smtp)
private String user = ""; //登录用户名
private String password = "";//登录密码
private String subject = "";//mail主题
public TestMail(String filepath) {
this.setPropertiesAttri(filepath);
}
private void setPropertiesAttri(String filepath) {
String path = filepath+"/config/mail.properties";
// FileOutputStream fos = null;
// try {
// fos = new FileOutputStream(path);
// } catch (FileNotFoundException e1) {
// e1.printStackTrace();
// }
// InputStream is = (InputStream)fos;
// InputStream is = getClass().getResourceAsStream("mail.properties");
Properties prop = new Properties();
try {
// prop.load(is);
prop.load(new FileInputStream(path));
} catch (IOException e) {
e.printStackTrace();
}
this.setSmtpHost(prop.get("SmtpHost").toString());
this.setUser(prop.get("User").toString());
this.setPassword(prop.get("Password").toString());
this.setSender(prop.get("Sender").toString());
this.setReceiver(prop.get("Receiver").toString());
this.setSubject(ExStr.CS(prop.get("Subject").toString()));
}
/** 设置发件人地址 */
public void setSender(String sender) {
this.sender = sender;
}
public String getSender() {
return sender;
}
/** 设置收件人地址 */
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getReceiver() {
return receiver;
}
/** 设置邮件发送服务器(smtp) */
public void setSmtpHost(String smtpHost) {
this.smtpHost = smtpHost;
}
public String getSmtpHost() {
return smtpHost;
}
/** 设置登录用户名 */
public void setUser(String user) {
this.user = user;
}
public String getUser() {
return user;
}
/** 设置登录密码 */
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
/** 设置mail主题 */
public void setSubject(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
/**
* 使用smtp发送邮件 主程序
* @throws MessagingException mail发送失败
*/
public void smtp(String content) throws MessagingException {
if (smtpHost == null)
throw new MessagingException("smtpHost not found");
if (user == null)
throw new MessagingException("user not found");
if (password == null)
throw new MessagingException("password not found");
Properties properties = new Properties();
properties.put("mail.smtp.host",smtpHost);//设置smtp主机
properties.put("mail.smtp.auth", "true");//使用smtp身份验证 Session session = Session.getInstance(properties,
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
//获得邮件会话对象
MimeMessage mimeMsg = new MimeMessage(session);//创建MIME邮件对象
if (sender != null)//设置发件人地址
{
mimeMsg.setFrom(new InternetAddress(sender));
}
if (receiver != null)//设置收件人地址
{
mimeMsg.setRecipients(Message.RecipientType.TO, parse(receiver));
}
if (subject != null)//设置邮件主题
{
mimeMsg.setSubject(subject, "GBK");
}
MimeBodyPart part = new MimeBodyPart();//mail内容部分
part.setText(content == null ? "" : content, "GBK");
//设置邮件格式为html cqc
part.setContent(content.toString(), "text/html;charset=GBK");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(part);//在 Multipart 中增加mail内容部分
mimeMsg.setContent(multipart);//增加 Multipart 到信息体
mimeMsg.setSentDate(new Date());//设置发送日期
Transport.send(mimeMsg);//发送邮件 }
/** 解析地址集合字符串 */
private InternetAddress[] parse(String addressSet) throws AddressException {
ArrayList list = new ArrayList();
StringTokenizer tokens = new StringTokenizer(addressSet, ";");
while (tokens.hasMoreTokens()) {
list.add(new InternetAddress(tokens.nextToken().trim()));
}
InternetAddress[] addressArray = new InternetAddress[list.size()];
list.toArray(addressArray);
return addressArray;
}
/**
* 供外部调用的接口
*/
public boolean sendMails(String content) {
int mailLen = 0;
int contentLen = 0;
if (content == null) {
return false;
}
try {
this.smtp(content);
} catch (MessagingException e) {
e.printStackTrace();
}
return true;
}
public static void main(String[] args) {
TestMail mail = new TestMail("C:/Tomcat 5.0/webapps/CAAgents/");
String content = "test";
mail.sendMails(content);
}
}~~~~~~~~
配置文件:mail.properties
#The Sender and the Receiver
#Tue Aug 23 13:20:05 CST 2005
Subject=hello
Sender=***@263.net
SmtpHost=smtp.263.net
Password=*****
Receiver=***@263.net
User=***