Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Multipart mp) throws MessagingException 

Source Link

Document

This method sets the Message's content to a Multipart object.

Usage

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java

private void addBody(MimeMessage msg) throws MessagingException {
    if (body != null) {
        Multipart multipart = new MimeMultipart();
        BodyPart bodyPart = new MimeBodyPart();

        bodyPart.setContent(body, contentType());
        multipart.addBodyPart(bodyPart);
        msg.setContent(multipart);
    }//from   w w  w.  ja  va 2s  . c  o  m
}

From source file:com.googlecode.psiprobe.tools.Mailer.java

private MimeMessage createMimeMessage(Session session, MailMessage mailMessage) throws MessagingException {
    InternetAddress[] to = createAddresses(mailMessage.getToArray());
    InternetAddress[] cc = createAddresses(mailMessage.getCcArray());
    InternetAddress[] bcc = createAddresses(mailMessage.getBccArray());
    if (to.length == 0) {
        to = InternetAddress.parse(defaultTo);
    }//ww w.  j av  a  2  s .co  m

    String subject = mailMessage.getSubject();
    if (subjectPrefix != null && !subjectPrefix.equals("")) {
        subject = subjectPrefix + " " + subject;
    }

    MimeMultipart content = new MimeMultipart("related");

    //Create attachments
    DataSource[] attachments = mailMessage.getAttachmentsArray();
    for (int i = 0; i < attachments.length; i++) {
        DataSource attachment = attachments[i];
        MimeBodyPart attachmentPart = createAttachmentPart(attachment);
        content.addBodyPart(attachmentPart);
    }

    //Create message body
    MimeBodyPart bodyPart = createMessageBodyPart(mailMessage.getBody(), mailMessage.isBodyHtml());
    content.addBodyPart(bodyPart);

    MimeMessage message = new MimeMessage(session);
    if (from == null) {
        message.setFrom(); //Uses mail.from property
    } else {
        message.setFrom(new InternetAddress(from));
    }
    message.setRecipients(Message.RecipientType.TO, to);
    message.setRecipients(Message.RecipientType.CC, cc);
    message.setRecipients(Message.RecipientType.BCC, bcc);
    message.setSubject(subject);
    message.setContent(content);
    return message;
}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email.//from   ww  w  . j av  a 2 s . com
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:com.emc.plants.service.impl.MailerBean.java

/** 
 * Create a mail message and send it.//from   ww w  . java  2  s  .c o  m
 *
 * @param customerInfo  Customer information.
 * @param orderKey
 * @throws MailerAppException
 */
public void createAndSendMail(CustomerInfo customerInfo, long orderKey) throws MailerAppException {
    try {
        EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey),
                customerInfo.getCustomerID());
        Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: "
                + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents());

        //Session mailSession = (Session) Util.getInitialContext().lookup(MAIL_SESSION);

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false));

        msg.setSubject(eMessage.getSubject());
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setText(eMessage.getHtmlContents(), "us-ascii");
        msg.setHeader("X-Mailer", "JavaMailer");
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        Transport.send(msg);

        Util.debug("\nMail sent successfully.");
    } catch (Exception e) {
        Util.debug("Error sending mail. Have mail resources been configured correctly?");
        Util.debug("createAndSendMail exception : " + e);
        e.printStackTrace();
        throw new MailerAppException("Failure while sending mail");
    }
}

From source file:fsi_admin.JSmtpConn.java

private boolean sendMsg(String HOST, String USERNAME, String PASSWORD, StringBuffer msj, Session session,
        MimeMessage mmsg, MimeMultipart multipart) {
    try {/*from ww  w .  j  a va  2s  . c  o m*/
        mmsg.setContent(multipart);
        // Create a transport.        
        Transport transport = session.getTransport();
        // Send the message.
        System.out.println(HOST + " " + USERNAME + " " + PASSWORD);
        transport.connect(HOST, USERNAME, PASSWORD);
        // Send the email.
        transport.sendMessage(mmsg, mmsg.getAllRecipients());
        transport.close();

        return true;
    } catch (MessagingException e) {
        e.printStackTrace();
        msj.append("Error de Mensajeria al enviar SMTP: " + e.getMessage());
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        msj.append("Error general de mensaje al enviar SMTP: " + ex.getMessage());
        return false;
    }

}

From source file:org.snopoke.util.Emailer.java

public void send() throws MessagingException {
    notNull(from, "From address can not be null");
    isTrue(!to.isEmpty() || !bcc.isEmpty(), "No TO or BCC addresses specified");

    MimeMessage message = getMessasge();

    // Cover wrap
    MimeBodyPart wrap = new MimeBodyPart();
    MimeMultipart cover = getCoverPart();
    wrap.setContent(cover);//from w w  w .  j  a v a  2s  . c  o m

    MimeMultipart content = new MimeMultipart("related");
    message.setContent(content);
    content.addBodyPart(wrap);

    addAttachments(content);

    Transport.send(message);
}

From source file:pt.webdetails.cdv.notifications.EmailOutlet.java

private boolean email(Alert alert) {

    try {//ww  w .j a  va2  s .co m

        // Get the session object
        final Session session = buildSession();

        // Create the message
        final MimeMessage msg = new MimeMessage(session);

        // From, to, etc.
        applyMessageHeaders(msg, alert);

        // Get main message multipart
        final Multipart multipartBody = getMultipartBody(session, alert);

        // Process attachments
        //final Multipart mainMultiPart = processAttachments(multipartBody);
        //msg.setContent(mainMultiPart);
        msg.setContent(multipartBody);

        // Send it

        //msg.setHeader("X-Mailer", MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;

    } catch (SendFailedException e) {
        logger.error(e);
    } catch (AuthenticationFailedException e) {
        logger.error(e);
    } catch (MessagingException me) {
        logger.error(me);
    } catch (IOException e) {
        logger.error(e);
    }

    return false;
}

From source file:com.eviware.soapui.impl.support.AbstractMockResponse.java

public String writeResponse(MockResult result, String responseContent) throws Exception {
    MimeMultipart mp = null;//from  www.  jav a 2  s  .  com

    Operation operation = getMockOperation().getOperation();

    // variables needed for both multipart sections....
    boolean isXOP = isMtomEnabled() && isForceMtom();
    StringToStringMap contentIds = new StringToStringMap();

    // only support multipart for wsdl currently.....
    if (operation instanceof WsdlOperation) {
        if (operation == null) {
            throw new IllegalStateException("Missing WsdlOperation for mock response");
        }

        // preprocess only if neccessary
        if (isMtomEnabled() || isInlineFilesEnabled() || getAttachmentCount() > 0) {
            try {
                mp = new MimeMultipart();

                WsdlOperation wsdlOperation = ((WsdlOperation) operation);
                MessageXmlObject requestXmlObject = createMessageXmlObject(responseContent, wsdlOperation);
                MessageXmlPart[] requestParts = requestXmlObject.getMessageParts();
                for (MessageXmlPart requestPart : requestParts) {
                    if (prepareMessagePart(mp, contentIds, requestPart)) {
                        isXOP = true;
                    }
                }
                responseContent = requestXmlObject.getMessageContent();
            } catch (Exception e) {
                SoapUI.logError(e);
            }
        }

        responseContent = removeEmptyContent(responseContent);
    }

    if (isStripWhitespaces()) {
        responseContent = XmlUtils.stripWhitespaces(responseContent);
    }

    MockRequest request = result.getMockRequest();
    request.getHttpResponse().setStatus(this.getResponseHttpStatus());

    ByteArrayOutputStream outData = new ByteArrayOutputStream();

    // non-multipart request?
    String responseCompression = getResponseCompression();
    if (!isXOP && (mp == null || mp.getCount() == 0) && getAttachmentCount() == 0) {
        String encoding = getEncoding();
        if (responseContent == null) {
            responseContent = "";
        }

        byte[] content = encoding == null ? responseContent.getBytes() : responseContent.getBytes(encoding);

        if (!result.getResponseHeaders().containsKeyIgnoreCase("Content-Type")) {
            result.setContentType(getContentType());
        }

        String acceptEncoding = result.getMockRequest().getRequestHeaders().get("Accept-Encoding", "");
        if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("GZIP")) {
            if (!headerExists("Content-Encoding", "gzip", result)) {
                result.addHeader("Content-Encoding", "gzip");
            }
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_GZIP, content));
        } else if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null
                && acceptEncoding.toUpperCase().contains("DEFLATE")) {
            result.addHeader("Content-Encoding", "deflate");
            outData.write(CompressionSupport.compress(CompressionSupport.ALG_DEFLATE, content));
        } else {
            outData.write(content);
        }
    } else // won't get here if rest at the moment...
    {
        // make sure..
        if (mp == null) {
            mp = new MimeMultipart();
        }

        // init root part
        initRootPart(responseContent, mp, isXOP);

        // init mimeparts
        AttachmentUtils.addMimeParts(this, Arrays.asList(getAttachments()), mp, contentIds);

        // create request message
        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(mp);
        message.saveChanges();
        MimeMessageMockResponseEntity mimeMessageRequestEntity = new MimeMessageMockResponseEntity(message,
                isXOP, this);

        result.addHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
        result.addHeader("MIME-Version", "1.0");
        mimeMessageRequestEntity.writeTo(outData);
    }

    if (outData.size() > 0) {
        byte[] data = outData.toByteArray();

        if (responseCompression.equals(CompressionSupport.ALG_DEFLATE)
                || responseCompression.equals(CompressionSupport.ALG_GZIP)) {
            result.addHeader("Content-Encoding", responseCompression);
            data = CompressionSupport.compress(responseCompression, data);
        }
        if (result.getResponseHeaders().get("Transfer-Encoding") == null) {
            result.addHeader("Content-Length", "" + data.length);
        }
        result.writeRawResponseData(data);
    }

    return responseContent;
}

From source file:org.talend.dataprep.api.service.mail.MailFeedbackSender.java

@Override
public void send(String subject, String body, String sender) {
    try {/* w ww.  ja v a2s  .  com*/
        final String recipientList = StringUtils.join((new HashSet<>(Arrays.asList(recipients))).toArray(),
                ',');
        subject = subjectPrefix + subject;
        body = bodyPrefix + "<br/>" + body + "<br/>" + bodySuffix;

        InternetAddress from = new InternetAddress(this.sender);
        InternetAddress replyTo = new InternetAddress(sender);

        Properties p = new Properties();
        p.put("mail.smtp.host", smtpHost);
        p.put("mail.smtp.port", smtpPort);
        p.put("mail.smtp.starttls.enable", "true");
        p.put("mail.smtp.auth", "true");

        MailAuthenticator authenticator = new MailAuthenticator(userName, password);
        Session sendMailSession = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(sendMailSession);
        msg.setFrom(from);
        msg.setReplyTo(new Address[] { replyTo });
        msg.addRecipients(Message.RecipientType.TO, recipientList);

        msg.setSubject(subject, "UTF-8");
        msg.setSentDate(new Date());
        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(body, "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        msg.setContent(mainPart);
        Transport.send(msg);

        LOGGER.debug("Sending mail:'{}' to '{}'", subject, recipients);
    } catch (Exception e) {
        throw new TDPException(APIErrorCodes.UNABLE_TO_SEND_MAIL, e);
    }
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * //from   w w w  .  j ava  2 s . c o m
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "ISO8859_1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart("alternative");
        MimeBodyPart htmlPart = new MimeBodyPart();
        MimeBodyPart textPart = new MimeBodyPart();

        textPart.setText(alternativeTextMessage, "ISO8859_1");
        textPart.setHeader("MIME-Version", "1.0");
        //textPart.setHeader("Content-Type", textPart.getContentType());
        textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\"");

        htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\"");
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\"");
        //htmlPart.setHeader("Content-Type", htmlPart.getContentType());

        multiPart.addBodyPart(textPart);
        multiPart.addBodyPart(htmlPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        msg.setHeader("MIME-Version", "1.0");
        msg.setHeader("Content-Type", multiPart.getContentType());

        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}