先贴一个,,velocity模板找不到路径
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
这是一个web项目使用的-选用class加载vm模版
<style type="text/css">
body {
font-family: Microsoft YaHei;
font-size: 12px;
}
p {
font-size: 18px;
}
.my-table {
border: 1px solid #000;
border-collapse: collapse;
}
.my-table tr {
border: 1px solid #000;
}
.my-table th {
border: 1px solid #000;
}
.my-table td {
border: 1px solid #000;
padding: 0px 5px;
}
td
{
text-align:center;
}
</style>
<body align="left">
<p>自动发邮件demo</p>
<table class="my-table" >
<tr style="background-color:#87CEFA" >
<th width="8%">序号</th>
<th width="8%">name</th>
<th width="10%" style="color: #00CC00">a</th>
<th width="10%">v</th>
<th width="10%">b</th>
<th width="10%">s</th>
<th width="11%">d</th>
</tr>
#foreach( $t in $data )
<tr>
<td>$!t.idx</td>
<td>$!t.name</td>
<td>$!t.a</td>
<td>$!t.s</td>
<td>$!t.s</td>
<td>$!t.s</td>
<td>$!t.s</td>
</tr>
#end
</table>
</body>
package service.zimpl.email;
import service.email.AutoEmailSendService;
import service.flagship.refund.order.IAutoEmailSendDao;
import util.MailSenderUtils;
import util.StringUtils;
import util.VmUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.velocity.VelocityContext;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
/**
* created by zhimin.xu on 2018/3/21
* discription:
*/
@Service
public class AutoEmailsendServiceImpl implements AutoEmailSendService {
private static final Logger logger = LoggerFactory.getLogger(AutoEmailsendServiceImpl.class);
@Autowired
private IAutoEmailSendDao iAutoEmailSendDao;
@Override
public void sendEmails() {
List<OrderContentBean> orderList = iAutoEmailSendDao.getOrderList();
String mailToStr = "abc@aa.com;xyz@xx.com";
String mailCcStr = "abc@aa.com;xyz@xx.com";
logger.info("get order message->{}", orderList);
if (orderList != null && CollectionUtils.isNotEmpty(orderList)) {
String title = "自动发邮件demo-" + DateTime.now().toString("yyyy-MM-dd");
String[] mailCc = getMailContacts(mailCcStr);
String[] mailTo = getMailContacts(mailToStr);
final VelocityContext velocityContext = new VelocityContext();
if (mailTo.length != 0) {
velocityContext.put("data", orderList);
final String content = VmUtils.getVmcontent(velocityContext, "/vm/auto_mail_report.vm");//模版地址
MailSenderUtils.send(title, content, mailTo, mailCc);
} else {
logger.info("not find mailTo.. ");
logger.error("not find mailTo..");
}
} else {
logger.info("order message is null , so dont need send mail");
}
}
/**
* 获取 数组格式的联系人邮件帐号
*
* @param contacts String
* @return
*/
private String[] getMailContacts(String contacts) {
Set<String> mailContacts = StringUtils.getSets(contacts);
return mailContacts.toArray(new String[mailContacts.size()]);
}
}
package util;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import java.util.Set;
/**
* created by zhimin.xu on 2018/3/23
* discription:处理 字符串
*/
public class StringUtils {
public static Set<String> getSets(String str) {
return Sets.newHashSet(Splitter.on(";").split(str));
}
}
获取vm模版代码
package util;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.StringWriter;
/**
* created by zhimin.xu on 2018/3/22
* discription:
*/
public class VmUtils {
private final static Logger logger = LoggerFactory.getLogger(VmUtils.class);
static String ENCODE = "UTF-8";
public static String getVmcontent(VelocityContext context, String vmPath) {
try {
// //设置velocity资源加载方式为file时的处理类--不行
// p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//设置velocity资源加载方式为class
VelocityEngine ve = new VelocityEngine();
ve.setProperty(Velocity.INPUT_ENCODING, ENCODE);
ve.setProperty(Velocity.OUTPUT_ENCODING, ENCODE);
//可选值:"class"--从classpath中读取,"file"--从文件系统中读取
ve.setProperty("resource.loader", "class");
ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
ve.init();
Template template = ve.getTemplate(vmPath);
logger.info("VmUtils template->{}", template);
StringWriter writer = new StringWriter();
template.merge(context, writer);
writer.flush();
writer.close();
return writer.toString();
} catch (Exception ex) {
logger.error("get vm error", ex);
throw new RuntimeException("get vm error" + ex.getMessage());
}
}
}
package util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.mail.DataSourceResolver;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.ImageHtmlEmail;
import org.apache.commons.mail.resolver.DataSourceCompositeResolver;
import org.apache.commons.mail.resolver.DataSourceFileResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* created by zhimin.xu on 2018/3/22
* discription:
*/
@Service
public class MailSenderUtils {
private static final Logger logger = LoggerFactory.getLogger(MailSenderUtils.class);
private static final String charset = "UTF-8";
private static String emailHostName="";//邮件服务器
public static void send(String title, String content, String[] mailTo, String[] mailCc) {
logger.info("check mail title->{} ,mailTo->{},mailCc->{}", title, mailTo, mailCc);
send(title, content, mailTo, mailCc, null, null);
}
/**
* @param title:邮件标题
* @param content:邮件内容
* @param mailList:收件人邮件列表
* @param cc:抄送人邮件列表
* @param attachPaths:附件路径
* @param descs:附件描述
*/
public static void send(String title, String content, String[] mailList, String[] cc, List<String> attachPaths,
List<String> descs) {
List<String> mails = filterMailAddr(title, content, mailList);
List<String> ccs = filterMailAddr(title, content, cc);
if (0 == mails.size()) {
return;
}
ImageHtmlEmail email = new ImageHtmlEmail();
try {
email.setHostName(emailHostName);
email.setSmtpPort(25);
email.setCharset(charset);
email.setFrom("发件人帐号", "AutoMail_Demo");
email.setAuthentication("发件人帐号", "发件人密码");
for (String mail : mails) {
email.addTo(mail);
}
for (String c : ccs) {
email.addCc(c);
}
EmailAttachment attachment = null;
if (CollectionUtils.isNotEmpty(attachPaths)) {
for (int i = 0; i < attachPaths.size(); i++) {
String attachPath = attachPaths.get(i);
attachment = new EmailAttachment();
attachment.setPath(attachPath);
attachment.setDescription(descs.get(i));
email.attach(attachment);
}
}
DataSourceResolver[] dataSourceResolvers = new DataSourceResolver[]{new DataSourceFileResolver()};
email.setDataSourceResolver(new DataSourceCompositeResolver(dataSourceResolvers));
email.setSubject(title);
email.setHtmlMsg(content);
email.getMailSession().getProperties().setProperty("mail.smtp.connectiontimeout", "2000");
email.getMailSession().getProperties().setProperty("mail.smtp.timeout", "5000");
email.send();
} catch (Exception e) {
logger.error(
"send error: title=" + title + ", content=" + content + ", mailList=" + Arrays.toString(mailList),
e);
}
}
private static List<String> filterMailAddr(String title, String content, String[] mailList) {
List<String> mails = new ArrayList<String>();
if (null == mailList) {
return mails;
}
for (String mail : mailList) {
if (null == mail || !mail.contains("@")) {
logger.error("mail addr err:" + mail + " title:" + title + " content:" + content);
} else {
mails.add(mail);
}
}
return mails;
}
}