import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.mail.internet.MimeUtility;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
public class SendMail {
// 邮件附件的存放位置
public static String getEmailFilePath() {
return emailFilePath;
}
public static void setEmailFilePath(String emailFilePath) {
SendMailImpl.emailFilePath = emailFilePath;
}
/** @Description 发送邮件
* @param protocol
* 邮箱协议
* @param fromEmail
* 来自邮箱地址
* @param password
* 邮箱密码
* @param toMail
* 要发送的邮件地址
* @param title
* 标题
* @param message
* 发送内容
* @param files
* 所有附件
* @return
* @throws Exception
* Map<String, Object>
*
*/
String password, String toMail, String title, String message,
String[] files) {
Map<String, Object> map = new HashMap<String, Object>();
File file = null;
EmailAttachment attachment = null;
try {
HtmlEmail email = new HtmlEmail();// HTML邮件
/* 配置参数 */
email.setHostName(protocol);
email.setAuthenticator(new DefaultAuthenticator(fromEmail, password));
email.setFrom(fromEmail);
email.setCharset("UTF-8");
/* 发送参数 */
email.setSubject(title);
email.setMsg(message);
email.addTo(toMail);
/* 添加附件 */
String filePath = emailFilePath;
for (int i = 0; i < files.length - 1; i++) {
file = new File(filePath + files[i]);
if (!file.exists()) {
map.put("rescode", -1);
map.put("msg", "找不到文件:" + files[i]);
return map;
}
attachment = new EmailAttachment();
attachment.setPath(filePath + files[i]);
attachment.setName(MimeUtility.encodeText(files[i]));
email.attach(attachment);
}
email.send();
map.put("rescode", 1);
map.put("msg", "成功");
} catch (Exception e) {
logger.error("发送邮件异常", e);
map.put("rescode", -2);
map.put("msg", "发送邮件异常");
}
return map;
}
}