java利用模板发送邮件_使用JavaMail实现发送模板邮件以及保存到发件箱

需要用到的jar包

1.freemarker-2.3.19.jar

2.javax.mail.jar

3.javax.activation.jar

本次测试邮箱是腾讯企业邮箱,其他未经测试。

做这个功能是因为我女朋友每个月都需要手动去发几十个人的考勤、考核邮件,实在是太过重复的做一件很乏味的事情,所以才有了这个程序,不过,界面是使用的控制台,简单一点。

核心代码展示

/**

* 发送邮件

* @author hezhao

* @Time 2017年3月13日 上午11:25:15

*/

public void send() {

System.out.println("正在发送邮件至:::["+to+"] ...");

// 设置邮件服务器

Properties prop = System.getProperties();

prop.put("mail.smtp.host", stmpmailServer);

prop.put("mail.smtp.auth", "true");

prop.put("mail.transport.protocol", this.send);

prop.put("mail.smtp.socketFactory.class",

"javax.net.ssl.SSLSocketFactory");

prop.put("mail.smtp.socketFactory.port", this.smtpport);

prop.put("mail.smtp.socketFactory.fallback", "false");

// 使用SSL,企业邮箱必需!

// 开启安全协议

MailSSLSocketFactory sf = null;

try {

sf = new MailSSLSocketFactory();

sf.setTrustAllHosts(true);

} catch (GeneralSecurityException e1) {

e1.printStackTrace();

}

prop.put("mail.smtp.starttls.enable", "true");

prop.put("mail.smtp.ssl.socketFactory", sf);

// 获取Session对象

Session session = Session.getDefaultInstance(prop, new Authenticator() {

// 此访求返回用户和密码的对象

@Override

protected PasswordAuthentication getPasswordAuthentication() {

PasswordAuthentication pa = new PasswordAuthentication(username,

password);

return pa;

}

});

// 设置session的调试模式,发布时取消

session.setDebug(true);

try {

// 封装Message对象

Message message = new MimeMessage(session);

// message.setFrom(new InternetAddress(from,from)); //设置发件人

// 设置自定义发件人昵称

String nick_from = "";

try {

nick_from = javax.mail.internet.MimeUtility.encodeText(this.nickname_from);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

message.setFrom(new InternetAddress(nick_from + " "));

// 设置自定义收件人昵称

String nick_to = "";

try {

nick_to = javax.mail.internet.MimeUtility.encodeText(this.nickname_to);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

message.setRecipient(Message.RecipientType.TO, new InternetAddress(nick_to + " "));// 设置收件人

message.setSubject(mailSubject);// 设置主题

message.setContent(mailContent, "text/html;charset=utf8");// 设置内容(设置字符集处理乱码问题)

message.setSentDate(new Date());// 设置日期

// 发送

Transport.send(message);

System.out.println("发送成功...");

//保存邮件到发件箱

saveEmailToSentMailFolder(message);

if(mailSubject.contains("考勤")){

FileLog.writeLog(this.nickname_to + " 发送成功");

}else{

FileLog.writeLog(this.nickname_to + " 发送成功");

}

} catch (Exception e) {

e.printStackTrace();

System.out.println("发送邮件异常...");

if(mailSubject.contains("考勤")){

FileLog.writeLog(this.nickname_to + " 发送失败");

}else{

FileLog.writeLog(this.nickname_to + " 发送失败");

}

}

}

保存至发件箱

/**

* 获取用户的发件箱文件夹

*

* @param message

* 信息

* @param store

* 存储

* @return

* @throws IOException

* @throws MessagingException

*/

private Folder getSentMailFolder(Message message, Store store)

throws IOException, MessagingException {

// 准备连接服务器的会话信息

Properties props = new Properties();

props.setProperty("mail.store.protocol", get);

props.setProperty("mail.imap.host", imapmailServer);

props.setProperty("mail.imap.port", "143");

/** QQ邮箱需要建立ssl连接 */

props.setProperty("mail.imap.socketFactory.class",

"javax.net.ssl.SSLSocketFactory");

props.setProperty("mail.imap.socketFactory.fallback", "false");

props.setProperty("mail.imap.starttls.enable", "true");

props.setProperty("mail.imap.socketFactory.port", imapport);

// 创建Session实例对象

Session session = Session.getInstance(props);

URLName urln = new URLName(get, imapmailServer, 143, null,

username, password);

// 创建IMAP协议的Store对象

store = session.getStore(urln);

store.connect();

// 获得发件箱

Folder folder = store.getFolder("Sent Messages");

// 以读写模式打开发件箱

folder.open(Folder.READ_WRITE);

return folder;

}

/**

* 保存邮件到发件箱

*

* @param message

* 邮件信息

*/

private void saveEmailToSentMailFolder(Message message) {

Store store = null;

Folder sentFolder = null;

try {

sentFolder = getSentMailFolder(message, store);

message.setFlag(Flag.SEEN, true); // 设置已读标志

sentFolder.appendMessages(new Message[] { message });

System.out.println("已保存到发件箱...");

} catch (Exception e) {

e.printStackTrace();

} finally {

// 判断发件文件夹是否打开如果打开则将其关闭

if (sentFolder != null && sentFolder.isOpen()) {

try {

sentFolder.close(true);

} catch (MessagingException e) {

e.printStackTrace();

}

}

// 判断邮箱存储是否打开如果打开则将其关闭

if (store != null && store.isConnected()) {

try {

store.close();

} catch (MessagingException e) {

e.printStackTrace();

}

}

}

}

获取模板内容

/**

* 得到模板内容

* @author hezhao

* @Time 2017年3月13日 下午1:01:08

* @param fileName

* @param map

* @return

*/

public String getMailText(String fileName,Map map){

String htmlText = null;

try {

Template template = config.getTemplate(fileName);

htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

} catch (IOException e) {

e.printStackTrace();

} catch (TemplateException e) {

e.printStackTrace();

}

return htmlText;

}

替换模板内容

FreemarkerUtil freemarkerUtil = null;

try {

freemarkerUtil = (FreemarkerUtil) context.getBean("freemarkerUtil");

} catch (Exception e) {

System.out.println("出现异常!!!");

e.printStackTrace();

}

String mailContent = freemarkerUtil.getMailText(fileName, map);

HTML模板(这个还是景洲帮我实现的)

table{border-collapse:collapse; text-align: center;font-size:12px;}

.yellow{background: #FFFF00;}

.blod{font-weight: bold;}

${title}
序号部门姓名入职时间考勤结果汇总 备注
正常出勤请假小时迟到分钟迟到扣款旷工天数休年假天数
${no}${dept}${name}${intotime}${workday}${outhour}${deletemin}${deletemoney}${kg}${year}${remark}

${bottom}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MailKit 是一个用于.NET平台的开源邮件库,它提供了连接和操作各种邮件服务器的功能。要连接腾讯企业邮箱,需要使用MailKit提供的API,并根据腾讯企业邮箱的设置进行配置。 首先,我们需要在项目中引用MailKit库。可以通过NuGet包管理器来安装,或者手动下载并添加到项目引用。 接下来,我们需要创建一个MailKit的SmtpClient对象来连接腾讯企业邮箱的SMTP服务器。这是发送邮件所必需的步骤。 ```csharp using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; class Program { static void Main() { using (var client = new SmtpClient()) { client.Connect("smtp.exmail.qq.com", 465, SecureSocketOptions.SslOnConnect); // 腾讯企业邮箱要求使用用户邮箱和密码进行身份验证 client.Authenticate("your_email@example.com", "your_password"); // 创建邮件对象 var message = new MimeMessage(); message.From.Add(new MailboxAddress("发件人名称", "from@example.com")); message.To.Add(new MailboxAddress("收件人名称", "to@example.com")); message.Subject = "邮件主题"; message.Body = new TextPart("plain") { Text = "邮件正文" }; // 发送邮件 client.Send(message); client.Disconnect(true); } } } ``` 需要注意的是,连接腾讯企业邮箱SMTP服务器时,通常使用ssl加密连接,并且要使用完整的邮箱地址和密码进行身份验证。 以上是基本的连接和发送邮件的示例,可以根据自己的需求进行进一步的配置和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值