仅仅实现了基本功能,如果需要有复杂的逻辑,在这个类的基础上进行扩展就行了,比如:邮件内容,邮箱,密码等基本信息放在配置文件里;实现群发引用该类,隔几秒发送一封邮箱灯等
package cn.test;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* Nov 26, 2008
*/
public class SendMail {
/**
* 授权,可以理解为用户登录吧
*
*/
public class MyAuthenticator extends Authenticator{
String username=null;
String password=null;
public MyAuthenticator(){}
public PasswordAuthentication check(String userName,String pwd){
username=userName;
password=pwd;
return getPasswordAuthentication();
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
}
public boolean send(){
boolean result=false;
Properties props = new Properties();
String smtpUser="[email protected]";
String smtpPwd="****";
String to="[email protected]";
props.put("mail.smtp.host", "smtp.canofy.cn");
props.put("mail.smtp.user", smtpUser);
props.put("mail.smtp.password", smtpPwd);
//有了这条语句才能通过验证,否则会出错
props.put("mail.smtp.auth", "true");
MyAuthenticator auth=new MyAuthenticator();
PasswordAuthentication pop=auth.check(smtpUser, smtpPwd);
Session mailSession=Session.getDefaultInstance(props,auth);
MimeMessage mimeMessage=new MimeMessage(mailSession);
try {
//发件人
mimeMessage.setFrom(this.getInternetAddress(smtpUser));
//收件人 Message.RecipientType.TO 发送,Message.RecipientType.CC 抄送,Message.RecipientType.BCC 暗送
mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
//标题
mimeMessage.setSubject("title");
//时间
mimeMessage.setSentDate(new Date());
//设置内容显示
BodyPart mdp=new MimeBodyPart();
mdp.setText(this.getContent());
//内容以text/html形式发送
// mdp.setContent(this.getContent(), "text/html;charset=gb2312");
Multipart mp=new MimeMultipart();
mp.addBodyPart(mdp);
mimeMessage.setContent(mp);
mimeMessage.saveChanges();
//发送邮件
Transport transport=mailSession.getTransport("smtp");
transport.send(mimeMessage);
// Transport.send(mimeMessage);
result=true;
} catch (Exception e) {
// System.out.println(e.getMessage());
e.printStackTrace();
}
return result;
}
public InternetAddress getInternetAddress(String mail) throws Exception{
return new InternetAddress(mail);
}
/**
* 获取邮件内容
* @return
*/
public String getContent(){
String result="";
result="content";
return result;
}
/**
* 获取邮件地址
* @return
*/
public String getMainAddr(){
String result="";
return result;
}
/**
* 获取邮件标题
* @return
*/
public String getMailTitle(){
String result="";
return result;
}
public static void main(String[] args){
SendMail sm=new SendMail();
if(sm.send()){
System.out.println("发送成功");
}else{
System.out.println("发送失败");
}
}
}
下面是一个应用,这只是部分代码:
package cn.mail;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import jp.mail.SendMail;
/**
* Sep 28, 2008
*/
public class TaskSend extends Thread {
private Logger logger=Logger.getLogger(TaskSend.class);
private List mailList = new ArrayList();//发邮件列表
private HashMap sendedMailMap = new HashMap();//已发送的邮件列表
private HashMap errorMailMap = new HashMap();//已发错了的邮件列表
public void run() {
String currentPath = System.getProperty("user.dir"); // 当前路径
String path_content = currentPath + "/mailContent.txt";//邮件内容
String path_title = currentPath + "/mailTitle.txt";//邮件主题
String path1 = currentPath + "/mailList.txt"; //发邮件列表
String path2 = currentPath + "/sendedList.txt"; //已发送的邮件列表
String path_error = currentPath + "/errorMail.txt"; //失败的邮件列表
//读邮件列表
this.getSendMailList(path1, path2, path_error);
String title = this.getFileContent(path_title);
String content= this.getFileContent(path_content);
//logger.info("邮件主题:" + title);
//logger.info("邮件内容:" + content);
long begin = System.currentTimeMillis();
String userName="";
String mail="";
boolean isresult = true;
int len=mailList.size();
int errCount = 0;
String line = "";
try{
SendMail send = null;
logger.info("begin.......");
for(int i=0;i<len;i++){
logger.error("total=" + len + " current=" + (i+1));
line = mailList.get(i).toString();
String temp[] = line.split("\t");
if(temp.length<2)
continue;
userName = temp[0];
mail = temp[1];
logger.info("stop=" + i);
sleep(1 * 1000 );
// if(i!=0 && i%200==0){
// logger.info("stop=" + i);
// sleep(10 * 1000 );
// }
send = new SendMail();
send.setContent(content.replaceAll("###USERNAME###", userName));
send.setTitle(title);
send.setRecipients(mail);
logger.info(line);
if(send.send()){
//发送成功
this.writeFile(path2, line+"\r\n");
}else{
errCount++;
//发送10次失败了
if(errCount==3){
errCount=0;
// return 0;
sleep(5 * 1000 );
}
//发送失败
this.writeFile(path_error, line+"\r\n");
}
}
logger.info("end.......");
}catch(Exception e){
logger.error("发邮件失败:" + line, e);
}
long end = System.currentTimeMillis();
logger.error("全部发送完毕,共用时:"+(end-begin));
// return 9;
}
/**
* 获取发邮件列表
* @param path1
* @param path2
*/
public void getSendMailList(String path1, String path2, String path3){
//读发邮件列表
this.readMailList(path1);
//读已成功发送的邮件列表
this.readSendedMailList(path2);
//读已出错的邮件列表
this.readErrorMailList(path3);
//如果已发送了的邮件就不再发送了
String key="";
if(this.sendedMailMap!=null && sendedMailMap.size()>0){
int i = 0;
while(i < mailList.size()){
//查找如果有则去掉已发邮件项
key = mailList.get(i).toString();
if(sendedMailMap.containsKey(key)){
mailList.remove(i);
//System.out.println(i+"="+key);
} else i++;
}
}
//处理错误的邮件列表不再发送
key="";
if(this.errorMailMap!=null && this.errorMailMap.size()>0){
int i = 0;
while(i < mailList.size()){
//查找如果有则去掉已发邮件项
key = mailList.get(i).toString();
if(errorMailMap.containsKey(key)){
mailList.remove(i);
//System.out.println(i+"="+key);
} else i++;
}
}
}
/**
* 读发邮件列表
* @param path
* @return
*/
public boolean readMailList(String path){
boolean isresult=true;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader bf =null;
try{
is = new FileInputStream(path);
isr = new InputStreamReader(is);
bf = new BufferedReader(isr);
String line = "";
while((line=bf.readLine())!=null){
//String temp[] = line.split("\t");
mailList.add(line);
}
bf.close();
isr.close();
is.close();
}catch(Exception e){
logger.error("读邮件列表出错:" + path, e);
isresult=false;
//
}
return isresult;
}
/**
* 读已成功发送的邮件列表
* @param path
* @return
*/
public boolean readSendedMailList(String path){
boolean isresult=true;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader bf =null;
try{
is = new FileInputStream(path);
isr = new InputStreamReader(is);
bf = new BufferedReader(isr);
String line = "";
while((line=bf.readLine())!=null){
//String temp[] = line.split("\t");
sendedMailMap.put(line, line);
}
bf.close();
isr.close();
is.close();
}catch(Exception e){
logger.error("读邮件列表出错:" + path, e);
isresult=false;
//
}
return isresult;
}
/**
* 出错误发送的邮件列表
* @param path
* @return
*/
public boolean readErrorMailList(String path){
boolean isresult=true;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader bf =null;
try{
is = new FileInputStream(path);
isr = new InputStreamReader(is);
bf = new BufferedReader(isr);
String line = "";
while((line=bf.readLine())!=null){
//String temp[] = line.split("\t");
this.errorMailMap.put(line, line);
}
bf.close();
isr.close();
is.close();
}catch(Exception e){
logger.error("读邮件列表出错:" + path, e);
isresult=false;
//
}
return isresult;
}
/**
* 获取文件内容
* @param path
* @return
*/
public String getFileContent(String path){
String context = "";
InputStream is = null;
InputStreamReader isr = null;
BufferedReader bf =null;
try{
is = new FileInputStream(path);
isr = new InputStreamReader(is,"utf-8");
bf = new BufferedReader(isr);
String line = "";
while((line=bf.readLine())!=null){
context += line;
}
bf.close();
isr.close();
is.close();
}catch(Exception e){
logger.error("读邮件内容出错:" + path, e);
}
return context;
}
/**
* 写文件
* @param path
* @param content
* @return
*/
public boolean writeFile(String path, String content){
File file = null;
try{
file = new File(path);
// System.out.println("文件的路径是:" + file);
BufferedWriter fileout = new BufferedWriter(new FileWriter(file, true));
fileout.write(content);
fileout.flush();
fileout.close();
}
catch(Exception e){
logger.error("写文件失败:" + file, e);
}
// System.out.println("写文件完毕");
return true;
}
/**
* @param args
*/
public static void main(String[] args) {
TaskSend task=new TaskSend();
task.start();
}
}