用java mail 实现Exchange发邮件的功能
1. 需要用到
microsoft.exchange.webservices
【java|Java mail Exchange Service】导入ews-java-api-2.0.jar, 在pom.xml文件里加入以下代码:
com.microsoft.ews-java-api
ews-java-api
2.0
2. 新建一个MailUtil.java类:
package com.spacex.util;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
/**
* 邮件发送工具实现类
*
* @author vino.dang
* @create 2017/01/05
*/
public class MailUtil {private static Logger logger = LoggerFactory.getLogger(MailUtil.class);
/**
* 发送邮件
* @param mail
* @return
*/
public static boolean sendEmail() {Boolean flag = false;
try {
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
//新建server版本
ExchangeCredentials credentials = new WebCredentials("vino", "abcd123", "spacex");
//用户名,密码,域名
service.setCredentials(credentials);
service.setUrl(new URI("https://outlook.spacex.com/EWS/Exchange.asmx"));
//outlook.spacex.com 改为自己的邮箱服务器地址
EmailMessage msg = new EmailMessage(service);
msg.setSubject("This is a test!");
//主题
msg.setBody(MessageBody.getMessageBodyFromText("this is a test! pls ignore it!"));
//内容
msg.getToRecipients().add("126@126.com");
//收件人
//msg.getCcRecipients().add("test2@test.com");
//抄送人
//msg.getAttachments().addFileAttachment("D:\\Downloads\\EWSJavaAPI_1.2\\EWSJavaAPI_1.2\\Getting started with EWS Java API.RTF");
//附件
msg.send();
//发送
flag = true;
} catch (Exception e) {
e.printStackTrace();
}return flag;
}public static void main(String[] args) {sendEmail();
}
}
以上为全部代码,有任何问题可以联系我!
请参照:
https://stackoverflow.com/questions/1713116/javamail-exchange-authentication/41529188#41529188
https://github.com/OfficeDev/ews-java-api/wiki/Getting-Started-Guide
推荐阅读
- Java|Java基础——数组
- 人工智能|干货!人体姿态估计与运动预测
- java简介|Java是什么(Java能用来干什么?)
- Java|规范的打印日志
- Linux|109 个实用 shell 脚本
- 程序员|【高级Java架构师系统学习】毕业一年萌新的Java大厂面经,最新整理
- Spring注解驱动第十讲--@Autowired使用
- SqlServer|sql server的UPDLOCK、HOLDLOCK试验
- jvm|【JVM】JVM08(java内存模型解析[JMM])
- 技术|为参加2021年蓝桥杯Java软件开发大学B组细心整理常见基础知识、搜索和常用算法解析例题(持续更新...)