Example usage for javax.mail.internet MimeMessage writeTo

List of usage examples for javax.mail.internet MimeMessage writeTo

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage writeTo.

Prototype

@Override
public void writeTo(OutputStream os) throws IOException, MessagingException 

Source Link

Document

Output the message as an RFC 822 format stream.

Usage

From source file:edu.unc.lib.dl.services.MailNotifier.java

public void sendIngestSuccessNotice(IngestProperties props, int ingestedCount) {
    String html = null, text = null;
    boolean logEmail = true;
    MimeMessage mimeMessage = null;
    try {//from   w  w w .ja  va2s.  com
        Template htmlTemplate = this.freemarkerConfiguration.getTemplate("IngestSuccessHtml.ftl",
                Locale.getDefault(), "utf-8");
        Template textTemplate = this.freemarkerConfiguration.getTemplate("IngestSuccessText.ftl",
                Locale.getDefault(), "utf-8");

        // put data into the model
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("numberOfObjects", new Integer(ingestedCount));
        model.put("irBaseUrl", this.irBaseUrl);
        List tops = new ArrayList();
        for (ContainerPlacement p : props.getContainerPlacements().values()) {
            HashMap om = new HashMap();
            om.put("pid", p.pid.getPid());
            om.put("label", p.label);
            tops.add(om);
        }
        model.put("tops", tops);

        StringWriter sw = new StringWriter();
        htmlTemplate.process(model, sw);
        html = sw.toString();
        sw = new StringWriter();
        textTemplate.process(model, sw);
        text = sw.toString();
    } catch (IOException e1) {
        throw new Error("Unable to load email template for Ingest Success", e1);
    } catch (TemplateException e) {
        throw new Error("There was a problem loading FreeMarker templates for email notification", e);
    }

    try {
        if (log.isDebugEnabled() && this.mailSender instanceof JavaMailSenderImpl) {
            ((JavaMailSenderImpl) this.mailSender).getSession().setDebug(true);
        }
        mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED);

        for (String addy : props.getEmailRecipients()) {
            message.addTo(addy);
        }
        message.setSubject("CDR ingest complete");

        message.setFrom(this.getRepositoryFromAddress());
        message.setText(text, html);

        // attach Events XML
        // Document events = new Document(aip.getEventLogger().getAllEvents());
        // message.addAttachment("events.xml", new JDOMStreamSource(events));
        this.mailSender.send(mimeMessage);
        logEmail = false;
    } catch (MessagingException e) {
        log.error("Unable to send ingest success email.", e);
    } catch (RuntimeException e) {
        log.error(e);
    } finally {
        if (mimeMessage != null && logEmail) {
            try {
                mimeMessage.writeTo(System.out);
            } catch (Exception e) {
                log.error("Could not log email message after error.", e);
            }
        }
    }

}

From source file:org.ktunaxa.referral.server.command.email.SendEmailCommand.java

public void execute(final SendEmailRequest request, final SendEmailResponse response) throws Exception {
    final String from = request.getFrom();
    if (null == from) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "from");
    }// w  w w .j a v  a 2s. c  om
    final String to = request.getTo();
    if (null == to) {
        throw new GeomajasException(ExceptionCode.PARAMETER_MISSING, "to");
    }

    response.setSuccess(false);
    final List<HttpGet> attachmentConnections = new ArrayList<HttpGet>();
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        public void prepare(MimeMessage mimeMessage) throws Exception {
            log.debug("Build mime message");

            addRecipients(mimeMessage, Message.RecipientType.TO, to);
            addRecipients(mimeMessage, Message.RecipientType.CC, request.getCc());
            addRecipients(mimeMessage, Message.RecipientType.BCC, request.getBcc());
            addReplyTo(mimeMessage, request.getReplyTo());
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setSubject(request.getSubject());
            // mimeMessage.setText(request.getText());

            List<String> attachments = request.getAttachmentUrls();
            MimeMultipart mp = new MimeMultipart();
            MimeBodyPart mailBody = new MimeBodyPart();
            mailBody.setText(request.getText());
            mp.addBodyPart(mailBody);
            if (null != attachments && !attachments.isEmpty()) {
                for (String url : attachments) {
                    log.debug("add mime part for {}", url);
                    MimeBodyPart part = new MimeBodyPart();
                    String filename = url;
                    int pos = filename.lastIndexOf('/');
                    if (pos >= 0) {
                        filename = filename.substring(pos + 1);
                    }
                    pos = filename.indexOf('?');
                    if (pos >= 0) {
                        filename = filename.substring(0, pos);
                    }
                    part.setFileName(filename);
                    String fixedUrl = url;
                    if (fixedUrl.startsWith("../")) {
                        fixedUrl = "http://localhost:8080/" + fixedUrl.substring(3);
                    }
                    fixedUrl = fixedUrl.replace(" ", "%20");
                    part.setDataHandler(new DataHandler(new URL(fixedUrl)));
                    mp.addBodyPart(part);
                }
            }
            mimeMessage.setContent(mp);
            log.debug("message {}", mimeMessage);
        }
    };
    try {
        if (request.isSendMail()) {
            mailSender.send(preparator);
            cleanAttachmentConnection(attachmentConnections);
            log.debug("mail sent");
        }
        if (request.isSaveMail()) {
            MimeMessage mimeMessage = new MimeMessage((Session) null);
            preparator.prepare(mimeMessage);
            // overwrite multipart body as we don't need the attachments
            mimeMessage.setText(request.getText());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mimeMessage.writeTo(baos);
            // add document in referral
            Crs crs = geoService.getCrs2(KtunaxaConstant.LAYER_CRS);
            List<InternalFeature> features = vectorLayerService.getFeatures(
                    KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs,
                    filterService.parseFilter(ReferralUtil.createFilter(request.getReferralId())), null,
                    VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES);
            InternalFeature orgReferral = features.get(0);
            log.debug("Got referral {}", request.getReferralId());
            InternalFeature referral = orgReferral.clone();
            List<InternalFeature> newFeatures = new ArrayList<InternalFeature>();
            newFeatures.add(referral);
            Map<String, Attribute> attributes = referral.getAttributes();
            OneToManyAttribute orgComments = (OneToManyAttribute) attributes
                    .get(KtunaxaConstant.ATTRIBUTE_COMMENTS);
            List<AssociationValue> comments = new ArrayList<AssociationValue>(orgComments.getValue());
            AssociationValue emailAsComment = new AssociationValue();
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_TITLE,
                    "Mail: " + request.getSubject());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATED_BY,
                    securitycontext.getUserName());
            emailAsComment.setDateAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CREATION_DATE, new Date());
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setStringAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_CONTENT,
                    new String(baos.toByteArray()));
            emailAsComment.setBooleanAttribute(KtunaxaConstant.ATTRIBUTE_COMMENT_INCLUDE_IN_REPORT, false);
            comments.add(emailAsComment);
            OneToManyAttribute newComments = new OneToManyAttribute(comments);
            attributes.put(KtunaxaConstant.ATTRIBUTE_COMMENTS, newComments);
            log.debug("Going to add mail as comment to referral");
            vectorLayerService.saveOrUpdate(KtunaxaConstant.LAYER_REFERRAL_SERVER_ID, crs, features,
                    newFeatures);
        }
        response.setSuccess(true);
    } catch (MailException me) {
        log.error("Could not send e-mail", me);
        throw new KtunaxaException(KtunaxaException.CODE_MAIL_ERROR, "Could not send e-mail");
    }
}

From source file:davmail.exchange.ews.EwsExchangeSession.java

/**
 * Get item content.//from  ww  w. ja v a2s .com
 *
 * @param itemId EWS item id
 * @return item content as byte array
 * @throws IOException on error
 */
protected byte[] getContent(ItemId itemId) throws IOException {
    GetItemMethod getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, true);
    byte[] mimeContent = null;
    try {
        executeMethod(getItemMethod);
        mimeContent = getItemMethod.getMimeContent();
    } catch (EWSException e) {
        LOGGER.warn("GetItem with MimeContent failed: " + e.getMessage());
    }
    if (getItemMethod.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        throw new HttpNotFoundException("Item " + itemId + " not found");
    }
    if (mimeContent == null) {
        LOGGER.warn("MimeContent not available, trying to rebuild from properties");
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            getItemMethod = new GetItemMethod(BaseShape.ID_ONLY, itemId, false);
            getItemMethod.addAdditionalProperty(Field.get("contentclass"));
            getItemMethod.addAdditionalProperty(Field.get("message-id"));
            getItemMethod.addAdditionalProperty(Field.get("from"));
            getItemMethod.addAdditionalProperty(Field.get("to"));
            getItemMethod.addAdditionalProperty(Field.get("cc"));
            getItemMethod.addAdditionalProperty(Field.get("subject"));
            getItemMethod.addAdditionalProperty(Field.get("date"));
            getItemMethod.addAdditionalProperty(Field.get("body"));
            executeMethod(getItemMethod);
            EWSMethod.Item item = getItemMethod.getResponseItem();

            MimeMessage mimeMessage = new MimeMessage((Session) null);
            mimeMessage.addHeader("Content-class", item.get(Field.get("contentclass").getResponseName()));
            mimeMessage.setSentDate(parseDateFromExchange(item.get(Field.get("date").getResponseName())));
            mimeMessage.addHeader("From", item.get(Field.get("from").getResponseName()));
            mimeMessage.addHeader("To", item.get(Field.get("to").getResponseName()));
            mimeMessage.addHeader("Cc", item.get(Field.get("cc").getResponseName()));
            mimeMessage.setSubject(item.get(Field.get("subject").getResponseName()));
            String propertyValue = item.get(Field.get("body").getResponseName());
            if (propertyValue == null) {
                propertyValue = "";
            }
            mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8");

            mimeMessage.writeTo(baos);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray()));
            }
            mimeContent = baos.toByteArray();

        } catch (IOException e2) {
            LOGGER.warn(e2);
        } catch (MessagingException e2) {
            LOGGER.warn(e2);
        }
        if (mimeContent == null) {
            throw new IOException("GetItem returned null MimeContent");
        }
    }
    return mimeContent;
}

From source file:com.flexoodb.common.FlexUtils.java

/**
* use this method to obtain a mimemessage with the file wrapped in it.
*
* @param  filename filename of the file.
* @param  data the file in bytes.// ww  w.j av  a  2s .  c  o  m
* @return a byte array of the mimemessage.
*/
static public byte[] wrapInMimeMessage(String filename, byte[] data) throws Exception {
    MimeMessage mimemessage = new MimeMessage(javax.mail.Session.getDefaultInstance(new Properties(), null));
    BodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    DataSource source = new ByteArrayDataSource(data, "application/octet-stream");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
    mimemessage.setContent(multipart);
    mimemessage.saveChanges();

    // finally pipe to an array so we can conver to string
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    mimemessage.writeTo(bos);
    return bos.toString().getBytes();
}

From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java

/**
 * Send email with Amazon Simple Email Service.
 * <p/>//from ww  w.j a v a2 s. c  o m
 * 
 * Please note that the sender (ie 'from') must be a verified address (see
 * {@link AmazonSimpleEmailService#verifyEmailAddress(com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest)}
 * ).
 * <p/>
 * 
 * Please note that the sender is a CC of the meail to ease support.
 * <p/>
 * 
 * @param subject
 * @param body
 * @param from
 * @param toAddresses
 * @throws MessagingException
 * @throws AddressException
 */
public void sendEmail(String subject, String body, AccessKey accessKey, KeyPair sshKeyPair,
        java.security.KeyPair x509KeyPair, X509Certificate x509Certificate,
        SigningCertificate signingCertificate, String from, String toAddress) {

    try {
        Session s = Session.getInstance(new Properties(), null);
        MimeMessage msg = new MimeMessage(s);

        msg.setFrom(new InternetAddress(from));
        msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress));
        msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(from));

        msg.setSubject(subject);

        MimeMultipart mimeMultiPart = new MimeMultipart();
        msg.setContent(mimeMultiPart);

        // body
        BodyPart plainTextBodyPart = new MimeBodyPart();
        mimeMultiPart.addBodyPart(plainTextBodyPart);
        plainTextBodyPart.setContent(body, "text/plain");

        // aws-credentials.txt / accessKey
        {
            BodyPart awsCredentialsBodyPart = new MimeBodyPart();
            awsCredentialsBodyPart.setFileName("aws-credentials.txt");
            StringWriter awsCredentialsStringWriter = new StringWriter();
            PrintWriter awsCredentials = new PrintWriter(awsCredentialsStringWriter);
            awsCredentials
                    .println("#Insert your AWS Credentials from http://aws.amazon.com/security-credentials");
            awsCredentials.println("#" + new DateTime());
            awsCredentials.println();
            awsCredentials.println("# ec2, rds & elb tools use accessKey and secretKey");
            awsCredentials.println("accessKey=" + accessKey.getAccessKeyId());
            awsCredentials.println("secretKey=" + accessKey.getSecretAccessKey());
            awsCredentials.println();
            awsCredentials.println("# iam tools use AWSAccessKeyId and AWSSecretKey");
            awsCredentials.println("AWSAccessKeyId=" + accessKey.getAccessKeyId());
            awsCredentials.println("AWSSecretKey=" + accessKey.getSecretAccessKey());

            awsCredentialsBodyPart.setContent(awsCredentialsStringWriter.toString(), "text/plain");
            mimeMultiPart.addBodyPart(awsCredentialsBodyPart);
        }
        // private ssh key
        {
            BodyPart keyPairBodyPart = new MimeBodyPart();
            keyPairBodyPart.setFileName(sshKeyPair.getKeyName() + ".pem.txt");
            keyPairBodyPart.setContent(sshKeyPair.getKeyMaterial(), "application/octet-stream");
            mimeMultiPart.addBodyPart(keyPairBodyPart);
        }

        // x509 private key
        {
            BodyPart x509PrivateKeyBodyPart = new MimeBodyPart();
            x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem.txt");
            String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate());
            x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/octet-stream");
            mimeMultiPart.addBodyPart(x509PrivateKeyBodyPart);
        }
        // x509 private key
        {
            BodyPart x509CertificateBodyPart = new MimeBodyPart();
            x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem.txt");
            String x509CertificatePem = Pems.pem(x509Certificate);
            x509CertificateBodyPart.setContent(x509CertificatePem, "application/octet-stream");
            mimeMultiPart.addBodyPart(x509CertificateBodyPart);
        }
        // Convert to raw message
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);

        RawMessage rawMessage = new RawMessage();
        rawMessage.setData(ByteBuffer.wrap(out.toString().getBytes()));

        ses.sendRawEmail(new SendRawEmailRequest().withRawMessage(rawMessage));
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:nl.nn.adapterframework.senders.MailSenderOld.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection<Recipient> recipients,
        Collection<Attachment> attachments) throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//from w w w .ja v a 2s  .c o  m
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Recipient recipient = (Recipient) iter.next();
            String value = recipient.value;
            String type = recipient.type;
            Message.RecipientType recipientType;
            if ("cc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.CC;
            } else if ("bcc".equalsIgnoreCase(type)) {
                recipientType = Message.RecipientType.BCC;
            } else {
                recipientType = Message.RecipientType.TO;
            }
            msg.addRecipient(recipientType, new InternetAddress(value));
            recipientsFound = true;
            if (log.isDebugEnabled()) {
                sb.append("[recipient [" + recipient + "]]");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            int counter = 0;
            iter = attachments.iterator();
            while (iter.hasNext()) {
                counter++;
                Attachment attachment = (Attachment) iter.next();
                Object value = attachment.getValue();
                String name = attachment.getName();
                if (StringUtils.isEmpty(name)) {
                    name = getDefaultAttachmentName() + counter;
                }
                log.debug("found attachment [" + attachment + "]");

                messageBodyPart = new MimeBodyPart();
                messageBodyPart.setFileName(name);

                if (value instanceof DataHandler) {
                    messageBodyPart.setDataHandler((DataHandler) value);
                } else {
                    messageBodyPart.setText((String) value);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Create message in specified folder./*w  w  w. ja va2s . c  om*/
 * Will overwrite an existing message with same messageName in the same folder
 *
 * @param folderPath  Exchange folder path
 * @param messageName message name
 * @param properties  message properties (flags)
 * @param mimeMessage MIME message
 * @throws IOException when unable to create message
 */
@Override
public void createMessage(String folderPath, String messageName, HashMap<String, String> properties,
        MimeMessage mimeMessage) throws IOException {
    String messageUrl = URIUtil.encodePathQuery(getFolderPath(folderPath) + '/' + messageName);
    PropPatchMethod patchMethod;
    List<PropEntry> davProperties = buildProperties(properties);

    if (properties != null && properties.containsKey("draft")) {
        // note: draft is readonly after create, create the message first with requested messageFlags
        davProperties.add(Field.createDavProperty("messageFlags", properties.get("draft")));
    }
    if (properties != null && properties.containsKey("mailOverrideFormat")) {
        davProperties.add(Field.createDavProperty("mailOverrideFormat", properties.get("mailOverrideFormat")));
    }
    if (properties != null && properties.containsKey("messageFormat")) {
        davProperties.add(Field.createDavProperty("messageFormat", properties.get("messageFormat")));
    }
    if (!davProperties.isEmpty()) {
        patchMethod = new PropPatchMethod(messageUrl, davProperties);
        try {
            // update message with blind carbon copy and other flags
            int statusCode = httpClient.executeMethod(patchMethod);
            if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode, ' ',
                        patchMethod.getStatusLine());
            }

        } finally {
            patchMethod.releaseConnection();
        }
    }

    // update message body
    PutMethod putmethod = new PutMethod(messageUrl);
    putmethod.setRequestHeader("Translate", "f");
    putmethod.setRequestHeader("Content-Type", "message/rfc822");

    try {
        // use same encoding as client socket reader
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mimeMessage.writeTo(baos);
        baos.close();
        putmethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
        int code = httpClient.executeMethod(putmethod);

        // workaround for misconfigured Exchange server
        if (code == HttpStatus.SC_NOT_ACCEPTABLE) {
            LOGGER.warn(
                    "Draft message creation failed, failover to property update. Note: attachments are lost");

            ArrayList<PropEntry> propertyList = new ArrayList<PropEntry>();
            propertyList.add(Field.createDavProperty("to", mimeMessage.getHeader("to", ",")));
            propertyList.add(Field.createDavProperty("cc", mimeMessage.getHeader("cc", ",")));
            propertyList.add(Field.createDavProperty("message-id", mimeMessage.getHeader("message-id", ",")));

            MimePart mimePart = mimeMessage;
            if (mimeMessage.getContent() instanceof MimeMultipart) {
                MimeMultipart multiPart = (MimeMultipart) mimeMessage.getContent();
                for (int i = 0; i < multiPart.getCount(); i++) {
                    String contentType = multiPart.getBodyPart(i).getContentType();
                    if (contentType.startsWith("text/")) {
                        mimePart = (MimePart) multiPart.getBodyPart(i);
                        break;
                    }
                }
            }

            String contentType = mimePart.getContentType();

            if (contentType.startsWith("text/plain")) {
                propertyList.add(Field.createDavProperty("description", (String) mimePart.getContent()));
            } else if (contentType.startsWith("text/html")) {
                propertyList.add(Field.createDavProperty("htmldescription", (String) mimePart.getContent()));
            } else {
                LOGGER.warn("Unsupported content type: " + contentType + " message body will be empty");
            }

            propertyList.add(Field.createDavProperty("subject", mimeMessage.getHeader("subject", ",")));
            PropPatchMethod propPatchMethod = new PropPatchMethod(messageUrl, propertyList);
            try {
                int patchStatus = DavGatewayHttpClientFacade.executeHttpMethod(httpClient, propPatchMethod);
                if (patchStatus == HttpStatus.SC_MULTI_STATUS) {
                    code = HttpStatus.SC_OK;
                }
            } finally {
                propPatchMethod.releaseConnection();
            }
        }

        if (code != HttpStatus.SC_OK && code != HttpStatus.SC_CREATED) {

            // first delete draft message
            if (!davProperties.isEmpty()) {
                try {
                    DavGatewayHttpClientFacade.executeDeleteMethod(httpClient, messageUrl);
                } catch (IOException e) {
                    LOGGER.warn("Unable to delete draft message");
                }
            }
            if (code == HttpStatus.SC_INSUFFICIENT_STORAGE) {
                throw new InsufficientStorageException(putmethod.getStatusText());
            } else {
                throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, code, ' ',
                        putmethod.getStatusLine());
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    } finally {
        putmethod.releaseConnection();
    }

    try {
        // need to update bcc after put
        if (mimeMessage.getHeader("Bcc") != null) {
            davProperties = new ArrayList<PropEntry>();
            davProperties.add(Field.createDavProperty("bcc", mimeMessage.getHeader("Bcc", ",")));
            patchMethod = new PropPatchMethod(messageUrl, davProperties);
            try {
                // update message with blind carbon copy
                int statusCode = httpClient.executeMethod(patchMethod);
                if (statusCode != HttpStatus.SC_MULTI_STATUS) {
                    throw new DavMailException("EXCEPTION_UNABLE_TO_CREATE_MESSAGE", messageUrl, statusCode,
                            ' ', patchMethod.getStatusLine());
                }

            } finally {
                patchMethod.releaseConnection();
            }
        }
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }

}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * @inheritDoc/*from  ww  w  .  j  a  v a2  s. c o m*/
 */
@Override
protected byte[] getContent(ExchangeSession.Message message) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    InputStream contentInputStream;
    try {
        try {
            try {
                contentInputStream = getContentInputStream(message.messageUrl);
            } catch (UnknownHostException e) {
                // failover for misconfigured Exchange server, replace host name in url
                restoreHostName = true;
                contentInputStream = getContentInputStream(message.messageUrl);
            }
        } catch (HttpNotFoundException e) {
            LOGGER.debug("Message not found at: " + message.messageUrl + ", retrying with permanenturl");
            contentInputStream = getContentInputStream(message.permanentUrl);
        }

        try {
            IOUtil.write(contentInputStream, baos);
        } finally {
            contentInputStream.close();
        }

    } catch (LoginTimeoutException e) {
        // throw error on expired session
        LOGGER.warn(e.getMessage());
        throw e;
    } catch (IOException e) {
        LOGGER.warn("Broken message at: " + message.messageUrl + " permanentUrl: " + message.permanentUrl
                + ", trying to rebuild from properties");

        try {
            DavPropertyNameSet messageProperties = new DavPropertyNameSet();
            messageProperties.add(Field.getPropertyName("contentclass"));
            messageProperties.add(Field.getPropertyName("message-id"));
            messageProperties.add(Field.getPropertyName("from"));
            messageProperties.add(Field.getPropertyName("to"));
            messageProperties.add(Field.getPropertyName("cc"));
            messageProperties.add(Field.getPropertyName("subject"));
            messageProperties.add(Field.getPropertyName("date"));
            messageProperties.add(Field.getPropertyName("htmldescription"));
            messageProperties.add(Field.getPropertyName("body"));
            PropFindMethod propFindMethod = new PropFindMethod(encodeAndFixUrl(message.permanentUrl),
                    messageProperties, 0);
            DavGatewayHttpClientFacade.executeMethod(httpClient, propFindMethod);
            MultiStatus responses = propFindMethod.getResponseBodyAsMultiStatus();
            if (responses.getResponses().length > 0) {
                MimeMessage mimeMessage = new MimeMessage((Session) null);

                DavPropertySet properties = responses.getResponses()[0].getProperties(HttpStatus.SC_OK);
                String propertyValue = getPropertyIfExists(properties, "contentclass");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Content-class", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "date");
                if (propertyValue != null) {
                    mimeMessage.setSentDate(parseDateFromExchange(propertyValue));
                }
                propertyValue = getPropertyIfExists(properties, "from");
                if (propertyValue != null) {
                    mimeMessage.addHeader("From", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "to");
                if (propertyValue != null) {
                    mimeMessage.addHeader("To", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "cc");
                if (propertyValue != null) {
                    mimeMessage.addHeader("Cc", propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "subject");
                if (propertyValue != null) {
                    mimeMessage.setSubject(propertyValue);
                }
                propertyValue = getPropertyIfExists(properties, "htmldescription");
                if (propertyValue != null) {
                    mimeMessage.setContent(propertyValue, "text/html; charset=UTF-8");
                } else {
                    propertyValue = getPropertyIfExists(properties, "body");
                    if (propertyValue != null) {
                        mimeMessage.setText(propertyValue);
                    }
                }
                mimeMessage.writeTo(baos);
            }
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Rebuilt message content: " + new String(baos.toByteArray()));
            }
        } catch (IOException e2) {
            LOGGER.warn(e2);
        } catch (DavException e2) {
            LOGGER.warn(e2);
        } catch (MessagingException e2) {
            LOGGER.warn(e2);
        }
        // other exception
        if (baos.size() == 0 && Settings.getBooleanProperty("davmail.deleteBroken")) {
            LOGGER.warn("Deleting broken message at: " + message.messageUrl + " permanentUrl: "
                    + message.permanentUrl);
            try {
                message.delete();
            } catch (IOException ioe) {
                LOGGER.warn("Unable to delete broken message at: " + message.permanentUrl);
            }
            throw e;
        }
    }

    return baos.toByteArray();
}

From source file:edu.unc.lib.dl.services.MailNotifier.java

/**
 * @param e/* w  ww. j a va2s  .co  m*/
 * @param user
 */
public void sendIngestFailureNotice(Throwable ex, IngestProperties props) {
    String html = null, text = null;
    MimeMessage mimeMessage = null;
    boolean logEmail = true;
    try {
        // create templates
        Template htmlTemplate = this.freemarkerConfiguration.getTemplate("IngestFailHtml.ftl",
                Locale.getDefault(), "utf-8");
        Template textTemplate = this.freemarkerConfiguration.getTemplate("IngestFailText.ftl",
                Locale.getDefault(), "utf-8");

        if (log.isDebugEnabled() && this.mailSender instanceof JavaMailSenderImpl) {
            ((JavaMailSenderImpl) this.mailSender).getSession().setDebug(true);
        }

        // create mail message
        mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED);

        // put data into the model
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("irBaseUrl", this.irBaseUrl);
        /*         List<ContainerPlacement> tops = new ArrayList<ContainerPlacement>();
                 tops.addAll(props.getContainerPlacements().values());
                 model.put("tops", tops);*/

        if (ex != null && ex.getMessage() != null) {
            model.put("message", ex.getMessage());
        } else if (ex != null) {
            model.put("message", ex.toString());
        } else {
            model.put("message", "No exception or error message available.");
        }

        // specific exception processing
        if (ex instanceof FilesDoNotMatchManifestException) {
            model.put("FilesDoNotMatchManifestException", ex);
        } else if (ex instanceof InvalidMETSException) {
            model.put("InvalidMETSException", ex);
            InvalidMETSException ime = (InvalidMETSException) ex;
            if (ime.getSvrl() != null) {
                Document jdomsvrl = ((InvalidMETSException) ex).getSvrl();
                DOMOutputter domout = new DOMOutputter();
                try {
                    org.w3c.dom.Document svrl = domout.output(jdomsvrl);
                    model.put("svrl", NodeModel.wrap(svrl));

                    // also dump SVRL to attachment
                    message.addAttachment("schematron-output.xml", new JDOMStreamSource(jdomsvrl));
                } catch (JDOMException e) {
                    throw new Error(e);
                }
            }
        } else if (ex instanceof METSParseException) {
            log.debug("putting MPE in the model");
            model.put("METSParseException", ex);
        } else {
            log.debug("IngestException without special email treatment", ex);
        }

        // attach error xml if available
        if (ex instanceof IngestException) {
            IngestException ie = (IngestException) ex;
            if (ie.getErrorXML() != null) {
                message.addAttachment("error.xml", new JDOMStreamSource(ie.getErrorXML()));
            }
        }

        model.put("user", props.getSubmitter());
        model.put("irBaseUrl", this.irBaseUrl);

        StringWriter sw = new StringWriter();
        htmlTemplate.process(model, sw);
        html = sw.toString();
        sw = new StringWriter();
        textTemplate.process(model, sw);
        text = sw.toString();

        // Addressing: to initiator if a person, otherwise to all members of
        // admin group
        if (props.getEmailRecipients() != null) {
            for (String r : props.getEmailRecipients()) {
                message.addTo(r);
            }
        }
        message.addTo(this.getAdministratorAddress(), "CDR Administrator");
        message.setSubject("CDR ingest failed");
        message.setFrom(this.getRepositoryFromAddress());
        message.setText(text, html);

        // attach Events XML
        // if (aip != null) {
        // /message.addAttachment("events.xml", new JDOMStreamSource(aip.getEventLogger().getAllEvents()));
        // }
        this.mailSender.send(mimeMessage);
        logEmail = false;
    } catch (MessagingException e) {
        log.error("Unable to send ingest fail email.", e);
    } catch (MailSendException e) {
        log.error("Unable to send ingest fail email.", e);
    } catch (UnsupportedEncodingException e) {
        log.error("Unable to send ingest fail email.", e);
    } catch (IOException e1) {
        throw new Error("Unable to load email template for Ingest Failure", e1);
    } catch (TemplateException e) {
        throw new Error("There was a problem loading FreeMarker templates for email notification", e);
    } finally {
        if (mimeMessage != null && logEmail) {
            try {
                mimeMessage.writeTo(System.out);
            } catch (Exception e) {
                log.error("Could not log email message after error.", e);
            }
        }
    }
}

From source file:nl.nn.adapterframework.senders.MailSender.java

protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType,
        String messageBase64, String charset, Collection recipients, Collection attachments)
        throws SenderException {

    StringBuffer sb = new StringBuffer();

    if (recipients == null || recipients.size() == 0) {
        throw new SenderException("MailSender [" + getName() + "] has no recipients for message");
    }//from  w  w  w.ja v  a2  s . c o  m
    if (StringUtils.isEmpty(from)) {
        from = defaultFrom;
    }
    if (StringUtils.isEmpty(subject)) {
        subject = defaultSubject;
    }
    log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject
            + "] to #recipients [" + recipients.size() + "]");

    if (StringUtils.isEmpty(messageType)) {
        messageType = defaultMessageType;
    }

    if (StringUtils.isEmpty(messageBase64)) {
        messageBase64 = defaultMessageBase64;
    }

    try {
        if (log.isDebugEnabled()) {
            sb.append("MailSender [" + getName() + "] sending message ");
            sb.append("[smtpHost=" + smtpHost);
            sb.append("[from=" + from + "]");
            sb.append("[subject=" + subject + "]");
            sb.append("[threadTopic=" + threadTopic + "]");
            sb.append("[text=" + message + "]");
            sb.append("[type=" + messageType + "]");
            sb.append("[base64=" + messageBase64 + "]");
        }

        if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) {
            message = decodeBase64ToString(message);
        }

        // construct a message  
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject, charset);
        if (StringUtils.isNotEmpty(threadTopic)) {
            msg.setHeader("Thread-Topic", threadTopic);
        }
        Iterator iter = recipients.iterator();
        boolean recipientsFound = false;
        while (iter.hasNext()) {
            Element recipientElement = (Element) iter.next();
            String recipient = XmlUtils.getStringValue(recipientElement);
            if (StringUtils.isNotEmpty(recipient)) {
                String typeAttr = recipientElement.getAttribute("type");
                Message.RecipientType recipientType = Message.RecipientType.TO;
                if ("cc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.CC;
                }
                if ("bcc".equalsIgnoreCase(typeAttr)) {
                    recipientType = Message.RecipientType.BCC;
                }
                msg.addRecipient(recipientType, new InternetAddress(recipient));
                recipientsFound = true;
                if (log.isDebugEnabled()) {
                    sb.append("[recipient(" + typeAttr + ")=" + recipient + "]");
                }
            } else {
                log.debug("empty recipient found, ignoring");
            }
        }
        if (!recipientsFound) {
            throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients");
        }

        String messageTypeWithCharset;
        if (charset == null) {
            charset = System.getProperty("mail.mime.charset");
            if (charset == null) {
                charset = System.getProperty("file.encoding");
            }
        }
        if (charset != null) {
            messageTypeWithCharset = messageType + ";charset=" + charset;
        } else {
            messageTypeWithCharset = messageType;
        }
        log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]");

        if (attachments == null || attachments.size() == 0) {
            //msg.setContent(message, messageType);
            msg.setContent(message, messageTypeWithCharset);
        } else {
            Multipart multipart = new MimeMultipart();
            BodyPart messageBodyPart = new MimeBodyPart();
            //messageBodyPart.setContent(message, messageType);
            messageBodyPart.setContent(message, messageTypeWithCharset);
            multipart.addBodyPart(messageBodyPart);

            iter = attachments.iterator();
            while (iter.hasNext()) {
                Element attachmentElement = (Element) iter.next();
                String attachmentText = XmlUtils.getStringValue(attachmentElement);
                String attachmentName = attachmentElement.getAttribute("name");
                String attachmentUrl = attachmentElement.getAttribute("url");
                String attachmentType = attachmentElement.getAttribute("type");
                String attachmentBase64 = attachmentElement.getAttribute("base64");
                if (StringUtils.isEmpty(attachmentType)) {
                    attachmentType = getDefaultAttachmentType();
                }
                if (StringUtils.isEmpty(attachmentName)) {
                    attachmentName = getDefaultAttachmentName();
                }
                log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url ["
                        + attachmentUrl + "]contents [" + attachmentText + "]");

                messageBodyPart = new MimeBodyPart();

                DataSource attachmentDataSource;
                if (!StringUtils.isEmpty(attachmentUrl)) {
                    attachmentDataSource = new URLDataSource(new URL(attachmentUrl));
                    messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource));
                }

                messageBodyPart.setFileName(attachmentName);

                if ("true".equalsIgnoreCase(attachmentBase64)) {
                    messageBodyPart.setDataHandler(decodeBase64(attachmentText));
                } else {
                    messageBodyPart.setText(attachmentText);
                }

                multipart.addBodyPart(messageBodyPart);
            }
            msg.setContent(multipart);
        }

        log.debug(sb.toString());
        msg.setSentDate(new Date());
        msg.saveChanges();
        // send the message
        putOnTransport(msg);
        // return the mail in mail-safe from
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        msg.writeTo(out);
        byte[] byteArray = out.toByteArray();
        return Misc.byteArrayToString(byteArray, "\n", false);
    } catch (Exception e) {
        throw new SenderException("MailSender got error", e);
    }
}