Example usage for javax.mail.internet MimeMultipart MimeMultipart

List of usage examples for javax.mail.internet MimeMultipart MimeMultipart

Introduction

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

Prototype

public MimeMultipart() 

Source Link

Document

Default constructor.

Usage

From source file:org.wandora.piccolo.actions.SendEmail.java

public void doAction(User user, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response,
        Application application) {/*from   w  w  w  .j  a  va2  s. c  o m*/
    try {

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpServer);
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        if (subject != null)
            message.setSubject(subject);
        if (from != null)
            message.setFrom(new InternetAddress(from));
        Vector<String> recipients = new Vector<String>();
        if (recipient != null) {
            String[] rs = recipient.split(",");
            String r = null;
            for (int i = 0; i < rs.length; i++) {
                r = rs[i];
                if (r != null)
                    recipients.add(r);
            }
        }

        MimeMultipart multipart = new MimeMultipart();

        Template template = application.getTemplate(emailTemplate, user);
        HashMap context = new HashMap();
        context.put("request", request);
        context.put("message", message);
        context.put("recipients", recipients);
        context.put("emailhelper", new MailHelper());
        context.put("multipart", multipart);
        context.putAll(application.getDefaultContext(user));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        template.process(context, baos);

        MimeBodyPart mimeBody = new MimeBodyPart();
        mimeBody.setContent(new String(baos.toByteArray(), template.getEncoding()), template.getMimeType());
        //            mimeBody.setContent(baos.toByteArray(),template.getMimeType());
        multipart.addBodyPart(mimeBody);
        message.setContent(multipart);

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpServer, smtpUser, smtpPass);
        Address[] recipientAddresses = new Address[recipients.size()];
        for (int i = 0; i < recipientAddresses.length; i++) {
            recipientAddresses[i] = new InternetAddress(recipients.elementAt(i));
        }
        transport.sendMessage(message, recipientAddresses);
    } catch (Exception e) {
        logger.writelog("WRN", e);
    }
}

From source file:org.smartloli.kafka.eagle.api.email.MailServiceImpl.java

/** Send mail in HTML format */
private boolean sendHtmlMail(MailSenderInfo mailInfo) {
    boolean enableMailAlert = SystemConfigUtils.getBooleanProperty("kafka.eagle.mail.enable");
    if (enableMailAlert) {
        SaAuthenticatorInfo authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            authenticator = new SaAuthenticatorInfo(mailInfo.getUserName(), mailInfo.getPassword());
        }/*from w  w  w. j  a  v a  2 s  . com*/
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            Message mailMessage = new MimeMessage(sendMailSession);
            Address from = new InternetAddress(mailInfo.getFromAddress());
            mailMessage.setFrom(from);
            Address[] to = new Address[mailInfo.getToAddress().split(",").length];
            int i = 0;
            for (String e : mailInfo.getToAddress().split(","))
                to[i++] = new InternetAddress(e);
            mailMessage.setRecipients(Message.RecipientType.TO, to);
            mailMessage.setSubject(mailInfo.getSubject());
            mailMessage.setSentDate(new Date());
            Multipart mainPart = new MimeMultipart();
            BodyPart html = new MimeBodyPart();
            html.setContent(mailInfo.getContent(), "text/html; charset=UTF-8");
            mainPart.addBodyPart(html);

            if (mailInfo.getImagesMap() != null && !mailInfo.getImagesMap().isEmpty()) {
                for (Entry<String, String> entry : mailInfo.getImagesMap().entrySet()) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    File file = new File(entry.getValue());
                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));
                    try {
                        mbp.setFileName(MimeUtility.encodeWord(entry.getKey(), "UTF-8", null));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    mbp.setContentID(entry.getKey());
                    mbp.setHeader("Content-ID", "<image>");
                    mainPart.addBodyPart(mbp);
                }
            }

            List<File> list = mailInfo.getFileList();
            if (list != null && list.size() > 0) {
                for (File f : list) {
                    MimeBodyPart mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(f.getAbsolutePath());
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(f.getName());
                    mainPart.addBodyPart(mbp);
                }

                list.clear();
            }

            mailMessage.setContent(mainPart);
            // mailMessage.saveChanges();
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
    return false;
}

From source file:voldemort.coordinator.HttpGetRequestExecutor.java

public void writeResponse(List<Versioned<byte[]>> versionedValues) throws Exception {

    MimeMultipart multiPart = new MimeMultipart();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    for (Versioned<byte[]> versionedValue : versionedValues) {

        byte[] responseValue = versionedValue.getValue();

        VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
        String serializedVectorClock = CoordinatorUtils.getSerializedVectorClock(vectorClock);

        // Create the individual body part for each versioned value of the
        // requested key
        MimeBodyPart body = new MimeBodyPart();
        try {//  w  ww  .  j  av  a2  s.c o m
            // Add the right headers
            body.addHeader(CONTENT_TYPE, "application/octet-stream");
            body.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
            body.addHeader(VoldemortHttpRequestHandler.X_VOLD_VECTOR_CLOCK, serializedVectorClock);
            body.setContent(responseValue, "application/octet-stream");
            body.addHeader(CONTENT_LENGTH, "" + responseValue.length);

            multiPart.addBodyPart(body);
        } catch (MessagingException me) {
            logger.error("Exception while constructing body part", me);
            outputStream.close();
            throw me;
        }
    }
    try {
        multiPart.writeTo(outputStream);
    } catch (Exception e) {
        logger.error("Exception while writing multipart to output stream", e);
        outputStream.close();
        throw e;
    }
    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
    responseContent.writeBytes(outputStream.toByteArray());

    // Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    // Set the right headers
    response.setHeader(CONTENT_TYPE, "multipart/binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");

    // Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());

    if (logger.isDebugEnabled()) {
        logger.debug("Response = " + response);
    }

    // Update the stats
    if (this.coordinatorPerfStats != null) {
        long durationInNs = System.nanoTime() - startTimestampInNs;
        this.coordinatorPerfStats.recordTime(Tracked.GET, durationInNs);
    }

    // Write the response to the Netty Channel
    this.getRequestMessageEvent.getChannel().write(response);
}

From source file:bo.com.offercruzmail.imp.FormadorMensajes.java

public static Multipart enviarInserccionExitosa(String id) throws MessagingException {
    Multipart cuerpo = new MimeMultipart();
    StringBuilder texto = new StringBuilder();
    texto.append(escapeHtml4("La inserccin se ha efectuado exitosamente. El identificador del registro es "));
    texto.append("<b>").append(id).append("<\b>");
    cuerpo.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(texto.toString()));
    return cuerpo;

}

From source file:net.ymate.module.mailsender.impl.DefaultMailSendProvider.java

@Override
public IMailSendBuilder create(final MailSendServerCfgMeta serverCfgMeta) {
    return new AbstractMailSendBuilder() {
        @Override//from w  w w . j a v  a  2 s.com
        public void send(final String content) throws Exception {
            __sendExecPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        MimeMessage _message = new MimeMessage(serverCfgMeta.createIfNeed());
                        //
                        for (String _to : getTo()) {
                            _message.addRecipient(Message.RecipientType.TO, new InternetAddress(_to));
                        }
                        for (String _cc : getCc()) {
                            _message.addRecipient(Message.RecipientType.CC, new InternetAddress(_cc));
                        }
                        for (String _bcc : getBcc()) {
                            _message.addRecipient(Message.RecipientType.BCC, new InternetAddress(_bcc));
                        }
                        //
                        if (getLevel() != null) {
                            switch (getLevel()) {
                            case LEVEL_HIGH:
                                _message.setHeader("X-MSMail-Priority", "High");
                                _message.setHeader("X-Priority", "1");
                                break;
                            case LEVEL_NORMAL:
                                _message.setHeader("X-MSMail-Priority", "Normal");
                                _message.setHeader("X-Priority", "3");
                                break;
                            case LEVEL_LOW:
                                _message.setHeader("X-MSMail-Priority", "Low");
                                _message.setHeader("X-Priority", "5");
                                break;
                            default:
                            }
                        }
                        //
                        String _charset = StringUtils.defaultIfEmpty(getCharset(), "UTF-8");
                        _message.setFrom(new InternetAddress(serverCfgMeta.getFromAddr(),
                                serverCfgMeta.getDisplayName(), _charset));
                        _message.setSubject(getSubject(), _charset);
                        // 
                        Multipart _container = new MimeMultipart();
                        // 
                        MimeBodyPart _textBodyPart = new MimeBodyPart();
                        if (getMimeType() == null) {
                            mimeType(IMailSender.MimeType.TEXT_PLAIN);
                        }
                        _textBodyPart.setContent(content, getMimeType().getMimeType() + ";charset=" + _charset);
                        _container.addBodyPart(_textBodyPart);
                        // ??<img src="cid:<CID_NAME>">
                        for (PairObject<String, File> _file : getAttachments()) {
                            if (_file.getValue() != null) {
                                MimeBodyPart _fileBodyPart = new MimeBodyPart();
                                FileDataSource _fileDS = new FileDataSource(_file.getValue());
                                _fileBodyPart.setDataHandler(new DataHandler(_fileDS));
                                if (_file.getKey() != null) {
                                    _fileBodyPart.setHeader("Content-ID", _file.getKey());
                                }
                                _fileBodyPart.setFileName(_fileDS.getName());
                                _container.addBodyPart(_fileBodyPart);
                            }
                        }
                        // ??
                        _message.setContent(_container);
                        Transport.send(_message);
                    } catch (Exception e) {
                        throw new RuntimeException(RuntimeUtils.unwrapThrow(e));
                    }
                }
            });
        }
    };
}

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

/** 
 * Create a mail message and send it./*from   ww w.  j  av a  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:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java

@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef) {
    if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) {
        // Get the email properties entered via Share Form
        String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME);
        String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME);
        String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME);

        // Get document filename
        Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef,
                ContentModel.PROP_NAME);
        if (filename == null) {
            throw new AlfrescoRuntimeException("Document filename is null");
        }//from  w  w  w  .j a v a2s.c o m
        String documentName = (String) filename;

        try {
            // Create mail session
            Properties mailServerProperties = new Properties();
            mailServerProperties = System.getProperties();
            mailServerProperties.put("mail.smtp.host", "localhost");
            mailServerProperties.put("mail.smtp.port", "2525");
            Session session = Session.getDefaultInstance(mailServerProperties, null);
            session.setDebug(false);

            // Define message
            Message message = new MimeMessage(session);
            String fromAddress = "training@alfresco.com";
            message.setFrom(new InternetAddress(fromAddress));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);

            // Create the message part with body text
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Create the Attachment part
            //
            //  Get the document content bytes
            byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName);
            if (documentData == null) {
                throw new AlfrescoRuntimeException("Document content is null");
            }
            //  Attach document
            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData,
                    new MimetypesFileTypeMap().getContentType(documentName))));
            messageBodyPart.setFileName(documentName);
            multipart.addBodyPart(messageBodyPart);

            // Put parts in message
            message.setContent(multipart);

            // Send mail
            Transport.send(message);

            // Set status on node as "sent via email"
            Map<QName, Serializable> properties = new HashMap<QName, Serializable>();
            properties.put(ContentModel.PROP_ORIGINATOR, fromAddress);
            properties.put(ContentModel.PROP_ADDRESSEE, to);
            properties.put(ContentModel.PROP_SUBJECT, subject);
            properties.put(ContentModel.PROP_SENTDATE, new Date());
            serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED,
                    properties);
        } catch (MessagingException me) {
            me.printStackTrace();
            throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage());
        }
    }
}

From source file:be.fedict.eid.dss.model.bean.TaskMDB.java

private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype,
        byte[] attachment) {
    LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\"");
    String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class);
    if (null == smtpServer || smtpServer.trim().isEmpty()) {
        LOG.warn("no SMTP server configured");
        return;//from  ww w  .ja  va2 s. c  o  m
    }
    String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class);
    if (null == mailFrom || mailFrom.trim().isEmpty()) {
        LOG.warn("no mail from address configured");
        return;
    }
    LOG.debug("mail from: " + mailFrom);

    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.from", mailFrom);

    String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class);
    if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) {
        subject = "[" + mailPrefix.trim() + "] " + subject;
    }

    Session session = Session.getInstance(props, null);
    try {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom();
        mimeMessage.setRecipients(RecipientType.TO, mailTo);
        mimeMessage.setSubject(subject);
        mimeMessage.setSentDate(new Date());

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(messageBody);

        Multipart multipart = new MimeMultipart();
        // first part is body
        multipart.addBodyPart(mimeBodyPart);

        // second part is attachment
        if (null != attachment) {
            MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype);
            attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource));
            multipart.addBodyPart(attachmentMimeBodyPart);
        }

        mimeMessage.setContent(multipart);
        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("send failed, exception: " + e.getMessage(), 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  2  s. 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");
    }
}