当前位置: 首页 > 工具软件 > EWS Java API > 使用案例 >

Java 通过EWS JAVA API发送exchange邮件

艾自强
2023-12-01

一、依赖的包

commons-codec-1.11.jar

commons-lang3-3.9.jar

commons-logging-1.2.jar

ews-java-api-2.0.jar

httpclient-4.5.10.jar

httpcore-4.4.12.jar

jcifs-2.1.11.jar

joda-time-2.4.jar

 
二、代码
 

package xx;

import java.net.URI;
import java.net.URISyntaxException;

import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.BodyType;
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;

public class GMCSend {

	private static String mailServer = "https://xxx.xx/ews/exchange.asmx";
    private static String user = "xx";
    private static String password = "xx";
    
	public static void main(String[] args) throws Exception {
		String subject = "测试";
		String[] to = {"xx@xx.com","xx@xx.com"};
		String[] cc = {};
		String bodyText = "hhhhh";
		send(subject, to, cc, bodyText);
	}

	
	/**
     * 发送不带附件的mail
     */
    public static void send(String subject, String[] to, String[] cc, String bodyText) throws Exception {
        doSend(subject, to, cc, bodyText, null);
    }
    
    /**
     * 发送带附件的mail
     */
    public static void doSend(String subject, String[] to, String[] cc, String bodyText, String[] attachmentPath) throws Exception {
        ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
        ExchangeCredentials credentials = new WebCredentials(user, password);
        service.setCredentials(credentials);
        try {
            service.setUrl(new URI(mailServer));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        EmailMessage msg = new EmailMessage(service);
        msg.setSubject(subject);
        MessageBody body = MessageBody.getMessageBodyFromText(bodyText);
        body.setBodyType(BodyType.HTML);
        msg.setBody(body);
        for (String s : to) {
            msg.getToRecipients().add(s);
        }
        if (cc != null) {
            for (String s : cc) {
                msg.getCcRecipients().add(s);
            }
        }
        if (attachmentPath != null && attachmentPath.length > 0) {
            for (int a = 0; a < attachmentPath.length; a++) {
                msg.getAttachments().addFileAttachment(attachmentPath[a]);
            }

        }
        msg.send();
    }
}

 

 类似资料: