Example usage for javax.mail.internet MimeMessage MimeMessage

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

Introduction

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

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {/*w w w .  j  ava  2 s . c  om*/

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.WsdlPackagingRequestFilter.java

protected String initWsdlRequest(WsdlRequest wsdlRequest, ExtendedPostMethod postMethod, String requestContent)
        throws Exception {
    MimeMultipart mp = null;/*from   w  w  w  .  j  a  v a2 s  .c  o  m*/

    StringToStringMap contentIds = new StringToStringMap();
    boolean isXOP = wsdlRequest.isMtomEnabled() && wsdlRequest.isForceMtom();

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

            MessageXmlObject requestXmlObject = new MessageXmlObject(wsdlRequest.getOperation(), requestContent,
                    true);
            MessageXmlPart[] requestParts = requestXmlObject.getMessageParts();
            for (MessageXmlPart requestPart : requestParts) {
                if (AttachmentUtils.prepareMessagePart(wsdlRequest, mp, requestPart, contentIds))
                    isXOP = true;
            }
            requestContent = requestXmlObject.getMessageContent();
        } catch (Throwable e) {
            SoapUI.log.warn("Failed to process inline/MTOM attachments; " + e);
        }
    }

    // non-multipart request?
    if (!isXOP && (mp == null || mp.getCount() == 0) && hasContentAttachmentsOnly(wsdlRequest)) {
        String encoding = System.getProperty("soapui.request.encoding",
                StringUtils.unquote(wsdlRequest.getEncoding()));
        byte[] content = StringUtils.isNullOrEmpty(encoding) ? requestContent.getBytes()
                : requestContent.getBytes(encoding);
        postMethod.setRequestEntity(new ByteArrayRequestEntity(content));
    } else {
        // make sure..
        if (mp == null)
            mp = new MimeMultipart();

        // init root part
        initRootPart(wsdlRequest, requestContent, mp, isXOP);

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

        // create request message
        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(mp);
        message.saveChanges();
        WsdlRequestMimeMessageRequestEntity mimeMessageRequestEntity = new WsdlRequestMimeMessageRequestEntity(
                message, isXOP, wsdlRequest);
        postMethod.setRequestEntity(mimeMessageRequestEntity);
        postMethod.setRequestHeader("Content-Type", mimeMessageRequestEntity.getContentType());
        postMethod.setRequestHeader("MIME-Version", "1.0");
    }

    return requestContent;
}

From source file:com.reizes.shiva.net.mail.Mail.java

public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject,
        String content) throws UnsupportedEncodingException, MessagingException {
    boolean parseStrict = false;
    MimeMessage message = new MimeMessage(getSessoin());
    InternetAddress address = InternetAddress.parse(from, parseStrict)[0];

    if (fromName != null) {
        address.setPersonal(fromName, charset);
    }//w w  w .  ja va 2  s. c  om

    message.setFrom(address);

    message.setRecipients(Message.RecipientType.TO, parseAddresses(to));

    if (cc != null) {
        message.setRecipients(Message.RecipientType.CC, parseAddresses(cc));
    }
    if (bcc != null) {
        message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc));
    }

    message.setSubject(subject, charset);

    message.setHeader("X-Mailer", "sendMessage");
    message.setSentDate(new java.util.Date()); //   

    Multipart multipart = new MimeMultipart();
    MimeBodyPart bodypart = new MimeBodyPart();
    bodypart.setContent(content, "text/html; charset=" + charset);
    multipart.addBodyPart(bodypart);

    message.setContent(multipart);
    Transport.send(message);
}

From source file:net.sf.jclal.util.mail.SenderEmail.java

/**
 * Send the email with the indicated parameters
 *
 * @param subject The subject/*  www.ja v a  2 s.c  o m*/
 * @param content The content
 * @param reportFile The reportFile to send
 */
public void sendEmail(String subject, String content, File reportFile) {

    // Get system properties
    Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);

    if (!user.isEmpty() && !pass.isEmpty()) {

        properties.setProperty("mail.user", user);

        properties.setProperty("mail.password", pass);
    }

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, toRecipients.toString());

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(content);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        if (attachReporFile) {

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile)));
            messageBodyPart.setFileName(reportFile.getName());
            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {

        Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e);
    }

}

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);/*  w  w  w .ja v a2  s.  com*/
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

    // add the Multipart to the message
    message.setContent(mp);

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:it.geosolutions.geobatch.mail.SendMailAction.java

public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {
    final Queue<EventObject> ret = new LinkedList<EventObject>();

    while (events.size() > 0) {
        final EventObject ev;
        try {/*from w ww .  j  av  a  2  s . c o  m*/
            if ((ev = events.remove()) != null) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace("Send Mail action.execute(): working on incoming event: " + ev.getSource());
                }

                File mail = (File) ev.getSource();

                FileInputStream fis = new FileInputStream(mail);
                String kmlURL = IOUtils.toString(fis);

                // /////////////////////////////////////////////
                // Send the mail with the given KML URL
                // /////////////////////////////////////////////

                // Recipient's email ID needs to be mentioned.
                String mailTo = conf.getMailToAddress();

                // Sender's email ID needs to be mentioned
                String mailFrom = conf.getMailFromAddress();

                // Get system properties
                Properties properties = new Properties();

                // Setup mail server
                String mailSmtpAuth = conf.getMailSmtpAuth();
                properties.put("mail.smtp.auth", mailSmtpAuth);
                properties.put("mail.smtp.host", conf.getMailSmtpHost());
                properties.put("mail.smtp.starttls.enable", conf.getMailSmtpStarttlsEnable());
                properties.put("mail.smtp.port", conf.getMailSmtpPort());

                // Get the default Session object.
                final String mailAuthUsername = conf.getMailAuthUsername();
                final String mailAuthPassword = conf.getMailAuthPassword();

                Session session = Session.getDefaultInstance(properties,
                        (mailSmtpAuth.equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                            protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(mailAuthUsername, mailAuthPassword);
                            }
                        } : null));

                try {
                    // Create a default MimeMessage object.
                    MimeMessage message = new MimeMessage(session);

                    // Set From: header field of the header.
                    message.setFrom(new InternetAddress(mailFrom));

                    // Set To: header field of the header.
                    message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));

                    // Set Subject: header field
                    message.setSubject(conf.getMailSubject());

                    String mailHeaderName = conf.getMailHeaderName();
                    String mailHeaderValule = conf.getMailHeaderValue();
                    if (mailHeaderName != null && mailHeaderValule != null) {
                        message.addHeader(mailHeaderName, mailHeaderValule);
                    }

                    String mailMessageText = conf.getMailContentHeader();

                    message.setText(mailMessageText + "\n\n" + kmlURL);

                    // Send message
                    Transport.send(message);

                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("Sent message successfully....");

                } catch (MessagingException exc) {
                    ActionExceptionHandler.handleError(conf, this, "An error occurrd when sent message ...");
                    continue;
                }
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Send Mail action.execute(): Encountered a NULL event: SKIPPING...");
                }
                continue;
            }
        } catch (Exception ioe) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Send Mail action.execute(): Unable to produce the output: ",
                        ioe.getLocalizedMessage(), ioe);
            }
            throw new ActionException(this, ioe.getLocalizedMessage(), ioe);
        }
    }

    return ret;
}

From source file:edu.harvard.iq.dataverse.MailServiceBean.java

public boolean sendSystemEmail(String to, String subject, String messageText) {

    boolean sent = false;
    String rootDataverseName = dataverseService.findRootDataverse().getName();
    String body = messageText + BundleUtil.getStringFromBundle("notification.email.closing",
            Arrays.asList(BrandingUtil.getInstallationBrandName(rootDataverseName)));
    logger.fine("Sending email to " + to + ". Subject: <<<" + subject + ">>>. Body: " + body);
    try {//from  w w w.j a va2  s. c  o  m
        MimeMessage msg = new MimeMessage(session);
        InternetAddress systemAddress = getSystemAddress();
        if (systemAddress != null) {
            msg.setFrom(systemAddress);
            msg.setSentDate(new Date());
            String[] recipientStrings = to.split(",");
            InternetAddress[] recipients = new InternetAddress[recipientStrings.length];
            for (int i = 0; i < recipients.length; i++) {
                try {
                    recipients[i] = new InternetAddress('"' + recipientStrings[i] + '"', "", charset);
                } catch (UnsupportedEncodingException ex) {
                    logger.severe(ex.getMessage());
                }
            }
            msg.setRecipients(Message.RecipientType.TO, recipients);
            msg.setSubject(subject, charset);
            msg.setText(body, charset);
            try {
                Transport.send(msg, recipients);
                sent = true;
            } catch (SMTPSendFailedException ssfe) {
                logger.warning("Failed to send mail to " + to + " (SMTPSendFailedException)");
            }
        } else {
            logger.fine("Skipping sending mail to " + to + ", because the \"no-reply\" address not set ("
                    + Key.SystemEmail + " setting).");
        }
    } catch (AddressException ae) {
        logger.warning("Failed to send mail to " + to);
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        logger.warning("Failed to send mail to " + to);
        me.printStackTrace(System.out);
    }
    return sent;
}

From source file:ua.aits.crc.controller.MainController.java

@RequestMapping(value = { "/sendmail/", "/sendmail" }, method = RequestMethod.GET)
public @ResponseBody String sendMail(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    request.setCharacterEncoding("UTF-8");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String text = request.getParameter("text");
    final String username = "office@crc.org.ua";
    final String password = "crossroad2000";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
            return new javax.mail.PasswordAuthentication(username, password);
        }//from w  w  w.  j a  v a 2 s.  c o m
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("office@crc.org.ua"));
        message.setSubject("Mail from site");
        message.setText("Name: " + name + "\nEmail: " + email + "\n\n" + text);
        Transport.send(message);
        return "done";
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:gov.nih.nci.cacis.cdw.CDWPendingLoader.java

public void loadPendingCDWDocuments(CDWLoader loader) {
    LOG.debug("Pending folder: " + cdwLoadPendingDirectory);
    LOG.info("SSSSSSS STARTED CDW LOAD SSSSSSSS");
    File pendingFolder = new File(cdwLoadPendingDirectory);
    FilenameFilter loadFileFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return true;
        }//from   w w w. ja  v a2s  .c o m
    };
    String[] loadFileNames = pendingFolder.list(loadFileFilter);
    LOG.info("Total Files to Load: " + loadFileNames.length);
    int filesLoaded = 0;
    int fileNumber = 0;
    for (String fileName : loadFileNames) {
        fileNumber++;
        LOG.info("Processing File [" + fileNumber + "] " + fileName);
        File loadFile = new File(cdwLoadPendingDirectory + "/" + fileName);
        try {
            final String[] params = StringUtils.split(fileName, "@@");
            String siteId = params[0];
            String studyId = params[1];
            String patientId = params[2];
            LOG.debug("SiteId: " + siteId);

            // the below code is not working, so parsing the file name for attributes.
            // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            // DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            // Document document = documentBuilder.parse(loadFile);
            // XPathFactory factory = XPathFactory.newInstance();
            // XPath xPath = factory.newXPath();
            // String siteID = xPath.evaluate("/caCISRequest/clinicalMetaData/@siteIdRoot", document);

            loader.load(FileUtils.getStringFromFile(loadFile), loader.generateContext(), studyId, siteId,
                    patientId);
            LOG.info(String.format("Successfully processed file [%s] [%s] and moving into [%s]", fileNumber,
                    loadFile.getAbsolutePath(), cdwLoadProcessedDirectory));
            org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadProcessedDirectory),
                    true);
            filesLoaded++;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", cdwLoadSenderHost);
                props.put("mail.smtp.port", cdwLoadSenderPort);

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(cdwLoadSenderUser, cdwLoadSenderPassword);
                    }
                });
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(cdwLoadSenderAddress));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(cdwLoadRecipientAddress));
                message.setSubject(cdwLoadNotificationSubject);
                message.setText(cdwLoadNotificationMessage + " [" + e.getMessage() + "]");

                Transport.send(message);
                org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadErrorDirectory),
                        true);
                // TODO add logic to send email
            } catch (Exception e1) {
                LOG.error(e1.getMessage());
                e1.printStackTrace();
            }
        }
    }
    LOG.info("Files Successfully Loaded: " + filesLoaded);
    LOG.info("EEEEEEE ENDED CDW LOAD EEEEEEE");
}

From source file:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/*from ww  w  . java  2s  .  c  o  m*/

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++)
                            System.out.println("         " + invalid[i]);
                    }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            System.out.println("         " + validUnsent[i]);
                    }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++)
                            System.out.println("         " + validSent[i]);
                    }
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            trans.close();
        } catch (MessagingException mex) { /* ignore */
        }
    }
}