如何使用microsoft exchange发送电子邮件附件?

时间:2014-05-29 14:50:53

标签: java email exchange-server exchange-server-2010

我想使用java通过Exchange服务器发送电子邮件附件。发送电子邮件工作正常:

ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials(username,password);
service.setCredentials(credentials);
service.setUrl(new URI(MailHost));

EmailMessage msg = new EmailMessage(service);
msg.setSubject("My Subject!");
msg.setBody(MessageBody.getMessageBodyFromText("My Message"));
msg.getToRecipients().add(mailTo);

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

我找到了解决方案HERE

public boolean sendEWSMail(String subject, String bodyContent, String to, String cc){
    ExchangeService service = new ExchangeService();
    EmailMessage msg = null; 
    ExchangeCredentials credentials = null;
    String domain = "domain name";
    if (domain == null || domain.equals("")) {
        credentials = new WebCredentials("username", 
                "password");
    } else {
        credentials = new WebCredentials("username", 
                "password", domain);
    }
    service.setCredentials(credentials);
    try {
        service.setUrl(new URI("Mail server URL"));
        msg = new EmailMessage(service);
        msg.setSubject(subject); 
        msg.setBody(MessageBody.getMessageBodyFromText(bodyContent));
        msg.getAttachments().addFileAttachment("Complete File Path");
        if(to == null || to.equals("")){
            LOGGER.warn("To distribution list is empty. Could not send the mail ");
        }else{
            String[] mailTos = to.split(";");
            for(String mailTo : mailTos){
                if(mailTo != null && !mailTo.isEmpty())
                msg.getToRecipients().add(mailTo);
            }
            if(cc != null && !cc.isEmpty()){
                String[] mailCCs = cc.split(";");
                for(String mailCc : mailCCs){
                    if(mailCc != null && !mailCc.equals(""))
                    msg.getCcRecipients().add(mailCc);
                }
            }
            msg.send();
            LOGGER.debug("Mail successfully send ");
            return true;
        }
    } catch (Exception e) {
        LOGGER.error("Exception occurred while sending EWS Mail ", e);
    }
    return false;
}

答案 1 :(得分:1)

现在(2016)您还可以使用new Outlook Email API并使用OutlookClient从Java代码发送RESTful请求。

另见here