Example usage for javax.mail.internet MimeBodyPart setFileName

List of usage examples for javax.mail.internet MimeBodyPart setFileName

Introduction

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

Prototype

@Override
public void setFileName(String filename) throws MessagingException 

Source Link

Document

Set the filename associated with this body part, if possible.

Usage

From source file:sendfile.java

public static void main(String[] args) {
    if (args.length != 5) {
        System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
        System.exit(1);/*from www  .j  a  v a 2  s .c  o  m*/
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    String filename = args[3];
    boolean debug = Boolean.valueOf(args[4]).booleanValue();
    String msgText1 = "Sending a file.\n";
    String subject = "Sending a file";

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());

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

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

        // set the Date: header
        msg.setSentDate(new Date());

        // send the message
        Transport.send(msg);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:org.vosao.utils.EmailUtil.java

/**
 * Send email with html content and attachments.
 * @param htmlBody//from   w w  w  .ja va2 s  .c  o m
 * @param subject
 * @param fromAddress
 * @param fromText
 * @param toAddress
 * @return null if OK or error message.
 */
public static String sendEmail(final String htmlBody, final String subject, final String fromAddress,
        final String fromText, final String toAddress, final List<FileItem> files) {

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    try {
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlBody, "text/html");
        htmlPart.setHeader("Content-type", "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);
        for (FileItem item : files) {
            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setFileName(item.getFilename());
            String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename()));
            DataSource ds = new ByteArrayDataSource(item.getData(), mimeType);
            attachment.setDataHandler(new DataHandler(ds));
            mp.addBodyPart(attachment);
        }
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress, fromText));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress));
        msg.setSubject(subject, "UTF-8");
        msg.setContent(mp);
        Transport.send(msg);
        return null;
    } catch (AddressException e) {
        return e.getMessage();
    } catch (MessagingException e) {
        return e.getMessage();
    } catch (UnsupportedEncodingException e) {
        return e.getMessage();
    }
}

From source file:org.vosao.utils.EmailUtil.java

/**
 * Send email with html content and attachments.
 * @param htmlBody//from   ww  w . j a  va2 s .com
 * @param subject
 * @param fromAddress
 * @param fromText
 * @param toAddress
 * @return null if OK or error message.
 */
public static String sendEmail(final String htmlBody, final String subject, final String fromAddress,
        final String fromText, final String toAddress, final List<FileItem> files) {

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    try {
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlBody, "text/html");
        htmlPart.setHeader("Content-type", "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);
        for (FileItem item : files) {
            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setFileName(item.getFilename());
            String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename()));
            if (mimeType.equals("text/plain")) {
                mimeType = MimeType.DEFAULT;
            }
            DataSource ds = new ByteArrayDataSource(item.getData(), mimeType);
            attachment.setDataHandler(new DataHandler(ds));
            mp.addBodyPart(attachment);
        }
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress, fromText));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress));
        msg.setSubject(subject, "UTF-8");
        msg.setContent(mp);
        Transport.send(msg);
        return null;
    } catch (AddressException e) {
        return e.getMessage();
    } catch (MessagingException e) {
        return e.getMessage();
    } catch (UnsupportedEncodingException e) {
        return e.getMessage();
    }
}

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

private static MimeBodyPart createAttachmentPart(DataSource attachment) throws MessagingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setDataHandler(new DataHandler(attachment));
    attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT);
    attachmentPart.setFileName(attachment.getName());
    return attachmentPart;
}

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

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {//from   w w  w.j a  v a  2 s.c  o  m

        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:org.latticesoft.util.resource.MessageUtil.java

/**
 * Sends the email.//from w  ww.ja v  a 2 s  .  c o m
 * @param info the EmailInfo containing the message and other details
 * @param p the properties to set in the environment when instantiating the session
 * @param auth the authenticator
 */
public static void sendMail(EmailInfo info, Properties p, Authenticator auth) {
    try {
        if (p == null) {
            if (log.isErrorEnabled()) {
                log.error("Null properties!");
            }
            return;
        }
        Session session = Session.getInstance(p, auth);
        session.setDebug(true);
        if (log.isInfoEnabled()) {
            log.info(p);
            log.info(session);
        }
        MimeMessage mimeMessage = new MimeMessage(session);
        if (log.isInfoEnabled()) {
            log.info(mimeMessage);
            log.info(info.getFromAddress());
        }
        mimeMessage.setFrom(info.getFromAddress());
        mimeMessage.setSentDate(new Date());
        List l = info.getToList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                if (log.isInfoEnabled()) {
                    log.info(addr);
                }
                mimeMessage.addRecipients(Message.RecipientType.TO, addr);
            }
        }
        l = info.getCcList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.CC, addr);
            }
        }
        l = info.getBccList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.BCC, addr);
            }
        }

        if (info.getAttachment().size() == 0) {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
                mimeMessage.setText(info.getContent(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
                mimeMessage.setText(info.getContent());
            }
            mimeMessage.setContent(info.getContent(), info.getContentType());
        } else {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
            }
            Multipart mp = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();
            if (info.getCharSet() != null) {
                body.setText(info.getContent(), info.getCharSet());
                body.setContent(info.getContent(), info.getContentType());
            } else {
                body.setText(info.getContent());
                body.setContent(info.getContent(), info.getContentType());
            }
            mp.addBodyPart(body);
            for (int i = 0; i < info.getAttachment().size(); i++) {
                String filename = (String) info.getAttachment().get(i);
                MimeBodyPart attachment = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(filename);
                attachment.setDataHandler(new DataHandler(fds));
                attachment.setFileName(MimeUtility.encodeWord(fds.getName()));
                mp.addBodyPart(attachment);
            }
            mimeMessage.setContent(mp);
        }
        Transport.send(mimeMessage);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error in sending email", e);
        }
    }
}

From source file:edu.harvard.med.screensaver.service.SmtpEmailService.java

private static void setFileAsAttachment(Message msg, String message, File file) throws MessagingException {
    MimeBodyPart p1 = new MimeBodyPart();
    p1.setText(message);//w w  w  .  j a  v  a 2s. c o m

    // Create second part
    MimeBodyPart p2 = new MimeBodyPart();

    // Put a file in the second part
    FileDataSource fds = new FileDataSource(file);
    p2.setDataHandler(new DataHandler(fds));
    p2.setFileName(fds.getName());

    // Create the Multipart.  Add BodyParts to it.
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(p1);
    mp.addBodyPart(p2);

    // Set Multipart as the message's content
    msg.setContent(mp);
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Convert a FileItem to a BodyPart//from  ww  w .  ja v  a2s  .co  m
 *
 * @param item
 * @return message body part
 * @throws MessagingException
 */
public static BodyPart fileitemToBodypart(FileItem item) throws MessagingException {
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileItemDataStore(item);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(source.getName());
    return messageBodyPart;
}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifySubscriptionDeleted(TemporaryMailContainer container) {
    try {//w  w  w . j ava2  s.c o m
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        Subscription obj = container.getObj();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s
        //maybe nice to use a template rather then sending raw xml.
        org.uddi.sub_v3.Subscription api = new org.uddi.sub_v3.Subscription();
        MappingModelToApi.mapSubscription(obj, api);
        String subscriptionResultXML = JAXBMarshaller.marshallToString(api, JAXBMarshaller.PACKAGE_SUBSCR_RES);
        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.subscriptionDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
        attachment.setFileName("uddiNotification.xml");
        mp.addBodyPart(attachment);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " "
                + StringEscapeUtils.escapeHtml(obj.getSubscriptionKey()));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:mitm.common.mail.BodyPartUtils.java

/**
 * Creates a MimeBodyPart with the provided message attached as a RFC822 attachment. 
 *//*from w ww . jav  a2 s  .  co m*/
public static MimeBodyPart toRFC822(MimeMessage message, String filename) throws MessagingException {
    MimeBodyPart bodyPart = new MimeBodyPart();

    bodyPart.setContent(message, "message/rfc822");
    /* somehow the content-Type header is not set so we need to set it ourselves */
    bodyPart.setHeader("Content-Type", "message/rfc822");
    bodyPart.setDisposition(Part.INLINE);
    bodyPart.setFileName(filename);

    return bodyPart;
}