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:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param file     The file./*from  w w w.j ava 2 s .  c  o m*/
 * @param contentType The Mime content type of the file.
 * @param fileName The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart.
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromBinaryFile(final File file, final String contentType,
        String fileName) throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        FileDataSource fileDataSource1 = new FileDataSource(file) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(fileDataSource1));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra binrfil", e);
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param pathToFile The complete path to the file - including file name.
 * @param contentType The Mime content type of the file.
 * @param fileName   The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart.//www. j a  v a 2  s  .com
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromBinaryFile(final String pathToFile, final String contentType,
        String fileName) throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        FileDataSource fileDataSource1 = new FileDataSource(pathToFile) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(fileDataSource1));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra binrfil", e);
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Helper method to create a MimeBodyPart from a binary file.
 *
 * @param data Data//from  w w w  .  j  a  v a 2 s .  c  om
 * @param contentType The Mime content type of the file.
 * @param fileName   The name of the file - as it will appear for the mail recipient.
 * @return The resulting MimeBodyPart.
 * @throws SystemException if the MimeBodyPart can't be created.
 */
public static MimeBodyPart createMimeBodyPartFromData(byte[] data, final String contentType, String fileName)
        throws SystemException {
    try {
        MimeBodyPart attachmentPart1 = new MimeBodyPart();
        ByteArrayDataSource dataSource = new ByteArrayDataSource(data, contentType) {
            @Override
            public String getContentType() {
                return contentType;
            }
        };
        attachmentPart1.setDataHandler(new DataHandler(dataSource));
        attachmentPart1.setFileName(fileName);
        return attachmentPart1;
    } catch (MessagingException e) {
        throw new SystemException("Feil ved generering av MimeBodyPart fra data[]", e);
    }
}

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  w  ww  .  j ava2 s.c  o m
 * @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:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {//from  ww  w . j a  v  a2 s . co  m
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:com.threewks.thundr.mail.JavaMailMailer.java

private void addAttachments(Multipart multipart, List<Attachment> attachments) throws MessagingException {
    for (Attachment attachment : attachments) {
        BasicViewRenderer response = render(attachment.view());
        byte[] base64Encoded = Base64.encodeToByte(response.getOutputAsBytes());

        InternetHeaders headers = new InternetHeaders();
        headers.addHeader(Header.ContentType, response.getContentType());
        headers.addHeader(Header.ContentTransferEncoding, "base64");

        MimeBodyPart part = new MimeBodyPart(headers, base64Encoded);
        part.setFileName(attachment.name());
        part.setDisposition(attachment.disposition().value());

        if (attachment.isInline()) {
            part.setContentID(attachment.contentId());
        }// www .ja  v  a2 s  .c o  m

        multipart.addBodyPart(part);
    }
}

From source file:org.openmrs.notification.mail.MailMessageSender.java

/**
 * Creates a MimeMultipart, so that we can have an attachment.
 *
 * @param message/*  w w w  . j a va  2 s  .  c o m*/
 * @return
 */
private MimeMultipart createMultipart(Message message) throws Exception {
    MimeMultipart toReturn = new MimeMultipart();

    MimeBodyPart textContent = new MimeBodyPart();
    textContent.setContent(message.getContent(), message.getContentType());

    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setContent(message.getAttachment(), message.getAttachmentContentType());
    attachment.setFileName(message.getAttachmentFileName());

    toReturn.addBodyPart(textContent);
    toReturn.addBodyPart(attachment);

    return toReturn;
}

From source file:org.eclipse.ecr.automation.core.mail.Composer.java

public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType,
        List<Blob> attachments) throws Exception {
    if (textType == null) {
        textType = "plain";
    }//from ww  w  .  j  a  v  a2 s  .c  o  m
    Mailer.Message msg = mailer.newMessage();
    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart body = new MimeBodyPart();
    String result = render(templateContent, ctx);
    body.setText(result, "UTF-8", textType);
    mp.addBodyPart(body);
    for (Blob blob : attachments) {
        MimeBodyPart a = new MimeBodyPart();
        a.setDataHandler(new DataHandler(new BlobDataSource(blob)));
        a.setFileName(blob.getFilename());
        mp.addBodyPart(a);
    }
    msg.setContent(mp);
    return msg;
}

From source file:org.infoglue.common.util.mail.MailService.java

/**
 * @param attachments // www .j av a 2s.  c o m
 *
 */
private Message createMessage(String from, String to, String bcc, String subject, String content,
        String contentType, String encoding, List attachments) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);
        String contentTypeWithEncoding = contentType + ";charset=" + encoding;

        // message.setContent(content, contentType);
        message.setFrom(createInternetAddress(from));
        //message.setRecipient(Message.RecipientType.TO,
        //      createInternetAddress(to));
        message.setRecipients(Message.RecipientType.TO, createInternetAddresses(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        // message.setSubject(subject);

        ((MimeMessage) message).setSubject(subject, encoding);
        MimeMultipart mp = new MimeMultipart();
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setDataHandler(new DataHandler(new StringDataSource(content, contentTypeWithEncoding, encoding)));
        mp.addBodyPart(mbp1);
        if (attachments != null) {
            for (Iterator it = attachments.iterator(); it.hasNext();) {
                File attachmentFile = (File) it.next();
                if (attachmentFile.exists()) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    attachment.setFileName(attachmentFile.getName());
                    attachment.setDataHandler(new DataHandler(new FileDataSource(attachmentFile)));
                    mp.addBodyPart(attachment);
                }
            }
        }
        message.setContent(mp);
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, contentTypeWithEncoding, encoding)));
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new SystemException("Unable to create the message.", e);
    }
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*from   ww w  .ja v a2  s  . co m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, @SuppressWarnings("unused") final String port,
        @SuppressWarnings("unused") final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;
    Boolean fail = false;

    ArrayList<String> userAndPass = new ArrayList<String>();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host); //$NON-NLS-1$
    props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    boolean usingSSL = false;
    if (usingSSL) {
        props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
        props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    }

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

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
    }

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));
        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toEMailAddr) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            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);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

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

        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                t.connect(host, userName, password);

                t.sendMessage(msg, msg.getAllRecipients());

                fail = false;
            } catch (MessagingException mex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
                instance.lastErrorMsg = mex.toString();

                Exception ex = null;
                if ((ex = mex.getNextException()) != null) {
                    ex.printStackTrace();
                    instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
                }

                //wrong username or password, get new one
                if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    fail = true;
                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) {//the user is done
                        return false;
                    }
                    // else
                    //try again
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }
            } finally {

                log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                t.close();
            }
        } while (fail && cnt < 6);

    } catch (MessagingException mex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        //mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return false;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        ex.printStackTrace();
    }

    if (fail) {
        return false;
    } //else
    return true;
}