java 邮件发送系统

    需求背景:公司需要群发邮件给不同的客户

    需求资源: 公司有收集到了客服邮箱地址 ,有搭建邮件发送系统<网上有开源搭建 这个直接问度娘吧>


     项目实现目的: 通过后台系统 直接发送邮件 

ps: 小弟 第一次发帖 有不当之处请海涵 大笑 好吧 直接贴代码


  如下一是 邮件控制 实体对象

package jade.email.po;

/**

 *  邮件实体

 * @author jade

 *

 */

public class Email {

  public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

public String getContext() {

return context;

}

public void setContext(String context) {

this.context = context;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public String getContextUrl() {

return contextUrl;

}

public void setContextUrl(String contextUrl) {

this.contextUrl = contextUrl;

}

public String getName() {

return Name;

}

public void setName(String name) {

Name = name;

}

public String getEmailUrl() {

return emailUrl;

}

public void setEmailUrl(String emailUrl) {

this.emailUrl = emailUrl;

}

public long getIsSend() {

return isSend;

}

public void setIsSend(long isSend) {

this.isSend = isSend;

}

private  long id;

  private String context;

  private String title;

  private String contextUrl;

  private String Name;

  private String emailUrl;

  private long isSend;

 

}


 如下是 邮件发送操作类



package jade.email.util;
import java.util.Random;
import org.apache.commons.mail.HtmlEmail;


/**
 * 邮件底层 服务 配置类
 * 
 * @author jade
 * 
 */
public class UtilMail {


transient static String hostName;
transient static String cpname = null;
transient static String MaxCountEmail = null;
transient static String username = null;
transient static String password = null;
transient static String frommail = null;
transient static HtmlEmail email = null;


static {
email = new HtmlEmail();
hostName = SystemConfig.getValue("hostName");
cpname = SystemConfig.getValue("cpname");
MaxCountEmail = SystemConfig.getValue("MaxCountEmail");
email.setHostName(hostName);


}


/**
* 邮件发送 方法

* @param to
*            发给谁
* @param msg
*            邮件内容
* @param subject
*            标题
* @return
*/
public static boolean sendEmail(String to, String msg, String subject) {
if (hostName == null || hostName.trim().equals("")
|| MaxCountEmail == null || MaxCountEmail.trim().equals(""))
throw new RuntimeException("邮件配置文件配置错误 请确认");


Random r = new Random();
int randomnum = r.nextInt(Integer.valueOf(MaxCountEmail));
username = SystemConfig.getValue("username" + randomnum);
password = SystemConfig.getValue("password" + randomnum);
frommail = SystemConfig.getValue("frommail" + randomnum);
cpname = SystemConfig.getValue("cpname");
email.setAuthentication(username, password); // 用户名和密码
try {


email.addTo(to); // 接收方
email.setSubject(subject); // 标题
email.setCharset("UTF-8");
email.setHtmlMsg(msg);
email.setFrom(frommail);
email.send();
return true;


} catch (Exception e) {
e.printStackTrace();
return false;
}


}


public static void main(String[] args) {
System.out.println(UtilMail.sendEmail("test@qq.com",
"I love you ", "test send Email"));


}


}



邮件发送 线程并发类:

package jade.email.com;
import jade.email.util.UtilMail;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;






/**
 * 邮件线程 封装
 * @author jade
 *
 */
public class sendMailThread  implements Runnable {


   

     transient  String path;
     transient  String contex;
     transient  String title;
     transient BufferedReader readEmail=null;
     
   

sendMailThread(){};
sendMailThread(String path,String contex,String title){
this.path=path;
this.contex=contex;
this.title=title;
try {
readEmail =new BufferedReader(new FileReader(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
}

}

@Override
public void run() {

try {
readTxtSend();
} catch (Exception e) {

e.printStackTrace();
}

}


public   void readTxtSend() throws Exception {



      while(readEmail.ready()){
      
      synchronized (readEmail) {   
      int count=0;
      String email=readEmail.readLine();
      if(email!=null){
      
      UtilMail.sendEmail(email, contex, title);
      
      System.out.println(Thread.currentThread().getName()+"    ="+email+"  title  =   "+ title);
      count++;
      }
      
      if(count>0 && count%1000==0){
      
      Thread.sleep(1000*60);
      }



}
}


}


public void wt(String s) throws IOException{

BufferedWriter bw=new BufferedWriter(new FileWriter(new File("/Users/jade/Documents/a.txt"),true));
bw.write(s);
      bw.newLine();
      bw.close();

}





/**
* 测试
* @param args
* @throws IOException 
* @throws InterruptedException 
*/
public static void main(String[] args) throws IOException, InterruptedException {






Runnable r= new sendMailThread("/Users/jade/Documents/a.txt","测试邮件","test");
Thread t =new Thread(r,"A");
Thread t1 =new Thread(r,"B");
Thread t2 =new Thread(r,"C");
Thread t3 =new Thread(r,"D");
 
t.start();
t1.start();
t2.start();
t3.start();
 

}

}


//  如下是 线程读取数据库类

package jade.email.com;


import java.util.Date;

import java.util.List;


import jade.email.po.Email;

import jade.email.util.UtilDB;


/***

 * 查询数据库

 * 

 * @author jade

 * 

 */

public class ReadDb implements Runnable {

final static String sql = "select * from t_email where isSend=1";

final static String sqlUpdate = "update  t_email set isSend=? where id=?";


String s = new String();


@Override

public void run() {


readDB();


}


private void readDB() {

synchronized (s) {


while (true) {

List<Email> list = UtilDB.findBySQL(sql, null, Email.class);

System.out.println(Thread.currentThread().getName() + "  :=  "

+ new Date());

if (list == null || list.size() == 0) {

try {

Thread.sleep(1000 * 60);

} catch (InterruptedException e) {

e.printStackTrace();

}

} else {


for (Email emaik : list) {


try {

UtilDB.excutSQL(sqlUpdate,

new Object[] { 0, emaik.getId() });

Thread.sleep(1000 * 10);

new Thread(new sendMailThread(emaik.getEmailUrl(),

emaik.getContext(), emaik.getTitle()))

.start();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}


}


}


}


}


}


如下是 数据库操作底层  《这个网上写法太多了 小弟不才随便写了下 有性能问题请指出 哈哈》

package jade.email.util;

import java.beans.BeanInfo;

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;


/**

 * 数据操作类

 * 

 * @author jade

 * 

 */

public class UtilDB {

static Connection conn = null; // 连接

static PreparedStatement ps = null; // 操作对象

static Statement pss = null; // 操作对象

static ResultSet res = null; // 结果


private static String div;

private static String username;

private static String password;

private static String url;


public UtilDB() {

}


static {

div = SystemConfig.getValue("div");

username = SystemConfig.getValue("username");

password = SystemConfig.getValue("password");

url = SystemConfig.getValue("url");

}


public static Connection getConnection() {

try {


Class.forName(div);


conn = DriverManager.getConnection(url, username, password);


} catch (Exception e) {


e.printStackTrace();

}


return conn;

}


/***

* 常规多数据源查询

* @param sql

* @return

*/

public static List findBysql(String sql) {

List rsall = new ArrayList();

try {

conn = getConnection();

ps = conn.prepareStatement(sql);

res = ps.executeQuery();

ResultSetMetaData rsmd = res.getMetaData(); // 取数据库的列

int numberOfColumns = rsmd.getColumnCount(); // 得到数据的列数,注意是从


while (res.next()) {

Object[] objects = new Object[numberOfColumns];

for (int i = 1; i <= numberOfColumns; i++) {

objects[i - 1] = res.getObject(i);

}

rsall.add(objects);

}


} catch (SQLException e) {

e.printStackTrace();

} finally {


close(conn, null, res);


}


return rsall;


}


/**

* 返回 对象

* @param sql

* @param parames

* @param className

* @return

*/

public static <T> T findObjectBySQL(String sql, Object[] parames,

Class<T> className) {


try {

conn = getConnection();

ps = conn.prepareStatement(sql);

T o = null;

/**

* 新增语句 传参 过程

*/

if (parames != null && parames.length > 0) {

for (int i = 0; i < parames.length; i++) {

ps.setObject(i + 1, parames[i]);

}

}


res = ps.executeQuery();


ResultSetMetaData rsmd = res.getMetaData();

int numberOfColumns = rsmd.getColumnCount();

HashMap<String, Object> coun = null;


while (res.next()) {


coun = new HashMap(numberOfColumns);


for (int r = 1; r < numberOfColumns + 1; r++) {


coun.put(rsmd.getColumnName(r), res.getObject(r));


}

return convertMap(className, coun);

}


}


catch (Exception e) {


e.printStackTrace();


} finally {

close(conn, ps, res);

}


return null;


}


/**

* 查询

* @param <T>

* @param sql

* @param parames

* @param clazz

* @return

*/

public static  <T> List<T> findBySQL(String sql, Object[] parames,

Class<T> className) {


List<T> rsall = new ArrayList<T>();

try {

conn = getConnection();

ps = conn.prepareStatement(sql);

/**

* 新增语句 传参 过程

*/

if (parames != null && parames.length > 0) {


for (int i = 0; i < parames.length; i++) {


ps.setObject(i + 1, parames[i]);

}

}


res = ps.executeQuery();

ResultSetMetaData rsmd = res.getMetaData();

int numberOfColumns = rsmd.getColumnCount();

HashMap<String, Object> coun = null;


while (res.next()) {


coun = new HashMap(numberOfColumns);


for (int r = 1; r < numberOfColumns + 1; r++) {


coun.put(rsmd.getColumnName(r), res.getObject(r));


}


rsall.add(convertMap(className, coun));

coun = null;

}


} catch (Exception e) {


e.printStackTrace();


} finally {

close(conn, ps, res); // 关闭连接

}


return rsall;

}


/**

* @param className

* @param coun

* @return

* @throws IntrospectionException

* @throws IllegalAccessException

* @throws InstantiationException

* @throws InvocationTargetException

*/

private static <T> T convertMap(Class<T> className,

HashMap<String, Object> coun) throws IntrospectionException,

IllegalAccessException, InstantiationException,

InvocationTargetException {

BeanInfo beanInfo = Introspector.getBeanInfo(className);

T t = className.newInstance();


for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {

String propertyName = descriptor.getName();

if (coun.containsKey(propertyName)) {


descriptor.getWriteMethod().invoke(t, coun.get(propertyName));

}

}

return t;

}


/**

* 关闭通用方法

* @param conn

* @param cs

*/

private static void close(Connection conn, PreparedStatement cs,

ResultSet res) {

try {


if (res != null) {

res.close();

}


if (cs != null) {

cs.close();

}


if (conn != null) {

conn.close();

}

} catch (Exception e) {

e.printStackTrace();


} finally {


}


}

public static Boolean excutSQL(String sql,Object [] parames){

Boolean isOk = false;

try {

conn = getConnection();

ps = conn.prepareStatement(sql);

if (parames != null && parames.length > 0) {

for (int i = 0; i < parames.length; i++) {

System.out.println(parames[i]);

ps.setObject(i + 1, parames[i]);

}

}

return isOk=ps.executeUpdate()==0?false:true;


} catch (SQLException e) {

e.printStackTrace();

} finally{

try {

ps.close();

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

return isOk;

}


public static void main(String[] args) {


}


}




     第一次发帖 项目找不到地方上传.... 以上就是 项目的核心类  如果有需要项目的 就留下邮件吧 或者留言说下如何 上传项目 微笑



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值