最近用java写个发邮件的东东,然后打成jar包,jar包可以放在任何地方邮件正常发送
要求 :
1、网络正常的情况下,可以发送;
2、网络不正常的时候,需要使用内网连接到外网,使用代理发送邮件。
部分代码拿出来分享一下:
package com.zyuc.mail;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import org.apache.log4j.Logger;
import com.zyuc.domParse.DomParseXml;
import com.zyuc.util.UtilTools;
/**
* 邮件发送
* @author wangxw
* 2011-10-26
*/
public class JmailConfig {
private static Logger logger = Logger.getLogger(JmailConfig.class);
private static Map map = new HashMap();
private static JmailFileRead jmailFileRead = new JmailFileRead();
public String Email_Text = new String();
private static JmailConfig mail = new JmailConfig();
/**
*构造函数 初始化参数信息
*/
public JmailConfig(){
//获得配置文件
String configPath = UtilTools.getPath()+File.separator+"JmailConfig.xml";
File file = new File(configPath);
//加载配置文件信息
if(file.exists()){
map = new DomParseXml().parseXml(configPath);
Email_Text = jmailFileRead.fileRead(map.get("Email_Text").toString());
}else{
logger.error("邮件配置文件未找到");
}
}
/**
* 邮件附件的添加
* @param multipart
* @param filePath
* @param fileName
* @param k
* @return boolean
*/
private boolean addMultipart(Multipart multipart, String filePath,
String fileName, int k) {
boolean flag = true;
try {
MimeBodyPart messageBodyPart = new MimeBodyPart();
if (k == 0) {
messageBodyPart.setText(Email_Text);
multipart.addBodyPart(messageBodyPart);
}
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
} catch (Exception e) {
flag = false;
logger.error("邮件附件的添加失败" + e.getMessage());
e.printStackTrace();
}
return flag;
}
/**
* 发送邮件信息配置
* @return boolean
*/
public boolean sendMail(){
boolean sendFlag = true;
final String username = map.get("Email_User").toString();
final String password = map.get("Email_Pswd").toString();
Session session;
//获得是否使用代理发送的标识
String Email_Proxy_Flag = map.get("Email_Proxy_Flag").toString();
if("1".equalsIgnoreCase(Email_Proxy_Flag)){
//若Email_Proxy_Flag==1则使用代理发送
try {
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
props.setProperty("proxySet", "true");
props.setProperty("mail.stmp.host", map.get("Email_Host").toString());
props.setProperty("http.proxyhost",map.get("Email_Proxy_Host").toString());
props.setProperty("http.proxyport",map.get("Email_Proxy_Port").toString());
session = Session.getDefaultInstance(props,
new Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(
username, password);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(map.get("Email_From").toString()));
//多个接受者
String[] to = map.get("Email_To").toString().split(";");
if (to != null) {
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
message.addRecipients(Message.RecipientType.TO, toAddress);
}
//多个抄送者
String[] cc = map.get("Email_Cc").toString().split(";");
if (null != cc) {
InternetAddress[] ccAddress = new InternetAddress[cc.length];
for (int j = 0; j < cc.length; j++) {
ccAddress[j] = new InternetAddress(cc[j]);
}
message.addRecipients(Message.RecipientType.CC, ccAddress);
}
message.setSubject(map.get("Email_Subject").toString());
//附件功能
Multipart multipart = new MimeMultipart();
String[] filepath = map.get("FilePath").toString().split(";");
String[] attachName = map.get("AttachName").toString().split(";");
if (null != filepath) {
for (int k = 0; k < filepath.length; k++) {
addMultipart(multipart, filepath[k], attachName[k], k);
}
} else if (null == filepath) {
message.setText(Email_Text);
}
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(map.get("Email_Host").toString(), username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
sendFlag = false;
logger.error("使用代理发送邮件出错" + e.getMessage());
e.printStackTrace();
}
}else{
//若Email_Proxy_Flag!=1则不使用代理发送
try {
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
props.setProperty("mail.stmp.host", map.get("Email_Host").toString());
session = Session.getDefaultInstance(props,
new Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(
username, password);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(map.get("Email_From").toString()));
//多个接收者
String[] to = map.get("Email_To").toString().split(";");
if (to != null) {
InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
message.addRecipients(Message.RecipientType.TO, toAddress);
}
//多个抄送者
String[] cc = map.get("Email_Cc").toString().split(";");
if (null != cc && cc.length > 0) {
InternetAddress[] ccAddress = new InternetAddress[cc.length];
for (int j = 0; j < cc.length; j++) {
ccAddress[j] = new InternetAddress(cc[j]);
}
message.addRecipients(Message.RecipientType.CC, ccAddress);
}
message.setSubject(map.get("Email_Subject").toString());
//附件功能
Multipart multipart = new MimeMultipart();
String[] filepath = map.get("FilePath").toString().split(";");
String[] attachName = map.get("AttachName").toString().split(";");
if (null != filepath && filepath.length > 0 && attachName.length > 0 && filepath.length == attachName.length) {
for (int k = 0; k < filepath.length; k++) {
addMultipart(multipart, filepath[k], attachName[k], k);
}
} else if (null == filepath) {
message.setText(Email_Text);
}
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(map.get("Email_Host").toString(), username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (Exception e) {
sendFlag = false;
logger.error("发送邮件出错" + e.getMessage());
e.printStackTrace();
}
}
return sendFlag;
}
public String returnMessage(){
boolean flag = mail.sendMail();
StringBuffer sb = new StringBuffer();
if(flag){
sb.append("\n").append("邮件发送已成功").append("\t").append("\n");
sb.append("邮件发送者:" + map.get("Email_From").toString()).append("\t").append("\n");
sb.append("邮件发送至:" + map.get("Email_To").toString()).append("\t").append("\n");
sb.append("邮件抄送给:" + map.get("Email_Cc").toString()).append("\t").append("\n");
sb.append("邮件正文为:" + map.get("Email_Text").toString()).append("\t").append("\n");
sb.append("发送时间是:" + UtilTools.getDate()).append("\t").append("\n");
}else{
sb.append("\n").append("邮件发送失败").append("\t").append("\n");
sb.append("发送时间是:" + UtilTools.getDate()).append("\t").append("\n");
}
return sb.toString();
}
public static void main(String args[]) {
logger.info("===============开始发送=================");
logger.info(mail.returnMessage());
logger.info("===============发送结束=================");
}
}