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:org.apache.jsieve.mailet.SieveMailboxMailet.java

/**
 * Deliver the original mail as an attachment with the main part being an error report.
 *
 * @param recipient/*  w  w w  .j av  a 2 s . c  o  m*/
 * @param aMail
 * @param ex
 * @throws MessagingException
 * @throws IOException 
 */
protected void handleFailure(MailAddress recipient, Mail aMail, Exception ex)
        throws MessagingException, IOException {
    String user = getUsername(recipient);

    MimeMessage originalMessage = aMail.getMessage();
    MimeMessage message = new MimeMessage(originalMessage);
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart noticePart = new MimeBodyPart();
    noticePart.setText(new StringBuilder().append(
            "An error was encountered while processing this mail with the active sieve script for user \"")
            .append(user).append("\". The error encountered was:\r\n").append(ex.getLocalizedMessage())
            .append("\r\n").toString());
    multipart.addBodyPart(noticePart);

    MimeBodyPart originalPart = new MimeBodyPart();
    originalPart.setContent(originalMessage, "message/rfc822");
    if ((originalMessage.getSubject() != null) && (!originalMessage.getSubject().trim().isEmpty())) {
        originalPart.setFileName(originalMessage.getSubject().trim());
    } else {
        originalPart.setFileName("No Subject");
    }
    originalPart.setDisposition(MimeBodyPart.INLINE);
    multipart.addBodyPart(originalPart);

    message.setContent(multipart);
    message.setSubject("[SIEVE ERROR] " + originalMessage.getSubject());
    message.setHeader("X-Priority", "1");
    message.saveChanges();

    storeMessageInbox(user, message);
}

From source file:com.googlecode.gmail4j.javamail.JavaMailGmailMessage.java

@Override
public void addAttachement(File file) {
    try {//from   w w  w  .j  a  v a 2 s .  co  m
        /* Check if email has already some contents. */
        Object content;
        try {
            content = this.source.getContent();
        } catch (IOException e) {
            /* If no content, then content is null.*/
            content = null;
            log.warn("Email content is empty.", e);
        }
        if (content != null) {
            if (content instanceof String) {
                /* This message is not multipart yet. Change it to multipart. */
                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText((String) this.source.getContent());

                Multipart multipart = new MimeMultipart();
                multipart.addBodyPart(messageBodyPart);
                this.source.setContent(multipart);
            }
        } else {
            /* No content, then create initial multipart content. */
            Multipart multipart = new MimeMultipart();
            this.source.setContent(multipart);
        }

        /* Get current content. */
        Multipart multipart = (Multipart) this.source.getContent();
        /* add attachment as a new part. */
        MimeBodyPart attachementPart = new MimeBodyPart();
        DataSource fileSource = new FileDataSource(file);
        DataHandler fileDataHandler = new DataHandler(fileSource);
        attachementPart.setDataHandler(fileDataHandler);
        attachementPart.setFileName(file.getName());
        multipart.addBodyPart(attachementPart);
    } catch (Exception e) {
        throw new GmailException("Failed to add attachement", e);
    }
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server//from ww  w. ja va 2  s .c  o  m
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

    final Session session = Session.getInstance(props, null);
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeBodyPart????Content-Disposition: inline
 *
 * @param file/*  www.  j a  v a  2  s  . c  om*/
 *            ?
 * @return MimeBodyPartContent-Disposition: inline?
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private MimeBodyPart createImagePart(InlineImageFile file)
        throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart imagePart = new MimeBodyPart();
    imagePart.setContentID(file.getContentId());
    imagePart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null));
    imagePart.setDataHandler(new DataHandler(file.getDataSource()));
    imagePart.setDisposition(MimeBodyPart.INLINE);
    return imagePart;
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server//  w ww  .ja  v  a 2  s  . c om
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:Implement.Service.AdminServiceImpl.java

@Override
public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException {
    String path = System.getProperty("catalina.base");
    MimeBodyPart logo = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png"));
    logo.setDataHandler(new DataHandler(source));
    logo.setFileName("logoIcon.png");
    logo.setDisposition(MimeBodyPart.INLINE);
    logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid

    MimeBodyPart facebook = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png"));
    facebook.setDataHandler(new DataHandler(source));
    facebook.setFileName("facebookIcon.png");
    facebook.setDisposition(MimeBodyPart.INLINE);
    facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid

    MimeBodyPart twitter = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png"));
    twitter.setDataHandler(new DataHandler(source));
    twitter.setFileName("twitterIcon.png");
    twitter.setDisposition(MimeBodyPart.INLINE);
    twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid

    MimeBodyPart insta = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png"));
    insta.setDataHandler(new DataHandler(source));
    insta.setFileName("instaIcon.png");
    insta.setDisposition(MimeBodyPart.INLINE);
    insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid

    MimeBodyPart youtube = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png"));
    youtube.setDataHandler(new DataHandler(source));
    youtube.setFileName("youtubeIcon.png");
    youtube.setDisposition(MimeBodyPart.INLINE);
    youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid

    MimeBodyPart pinterest = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png"));
    pinterest.setDataHandler(new DataHandler(source));
    pinterest.setFileName("pinterestIcon.png");
    pinterest.setDisposition(MimeBodyPart.INLINE);
    pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid

    String content = "<div style=' width: 507px;background-color: #f2f2f4;'>"
            + "    <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>"
            + "        <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>"
            + "        <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + "    </div>"
            + "    <div style=' padding: 50px;margin-bottom: 20px;'>" + "        <div id='email-form'>"
            + "            <div style='margin-bottom: 20px'>" + "                Hi " + emailData.getLastName()
            + " ,<br/>" + "                Your package " + emailData.getLastestPackageName()
            + " has been approved" + "            </div>" + "            <div style='margin-bottom: 20px'>"
            + "                Thanks,<br/>" + "                Youtripper team\n" + "            </div>"
            + "        </div>" + "        <div style='border-top: solid 1px #c4c5cc;text-align:center;'>"
            + "            <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>"
            + "            <div>"
            + "                <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>"
            + "                <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>"
            + "                <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>"
            + "                <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>"
            + "                <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>"
            + "            </div>"
            + "            <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon,"
            + "                <br>Pravet, Bangkok, Thailand 10250</p>" + "        </div>" + "    </div>"
            + "</div>";

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);/* w  ww.  ja va  2s .  co m*/
    mp.addBodyPart(logo);
    mp.addBodyPart(facebook);
    mp.addBodyPart(twitter);
    mp.addBodyPart(insta);
    mp.addBodyPart(youtube);
    mp.addBodyPart(pinterest);

    final String username = "noreply@youtripper.com";
    final String password = "Tripper190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("noreply@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail()));
    message.setSubject("Package Approved!");
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);
    return true;
}

From source file:org.pentaho.reporting.platform.plugin.SimpleEmailComponent.java

private void processSpecificAttachment(final MimeMultipart mixedMultipart, final IContentItem attachmentContent)
        throws IOException, MessagingException {

    // Add this attachment

    if (attachmentContent != null) {

        final ByteArrayDataSource dataSource = new ByteArrayDataSource(attachmentContent.getInputStream(),
                attachmentContent.getMimeType());
        final MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(getAttachmentName());
        mixedMultipart.addBodyPart(attachmentBodyPart);

    }//ww w.  java 2s . com

}

From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java

private MimeBodyPart constructEmail(int index, ApplicationGroup appGroup, StringBuilder body)
        throws IOException, MessagingException {

    if (index == 0 && !StringUtils.isEmpty(headerNote))
        body.append(headerNote);//from w w  w  .  j a  v  a  2  s. co m

    numberFormatter.setMaximumFractionDigits(1);
    numberFormatter.setMinimumFractionDigits(1);

    File file = createImage(appGroup);

    if (file == null)
        return null;

    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    String link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks),
            end);
    body.append(String.format("<b><h4><a href='%s'>%s</a> Weekly Costs:</h4></b>", link,
            appGroup.getDisplayName()));

    body.append("<table style=\"border: 1px solid #DDD; border-collapse: collapse\">");
    body.append(
            "<tr style=\"background-color: whiteSmoke;text-align:center\" ><td style=\"border-left: 1px solid #DDD;\"></td>");
    for (int i = 0; i <= accounts.size(); i++) {
        int cols = i == accounts.size() ? 1 : regions.size();
        String accName = i == accounts.size() ? "total" : accounts.get(i).name;
        body.append(String.format(
                "<td style=\"border-left: 1px solid #DDD;font-weight: bold;padding: 4px\" colspan='%d'>", cols))
                .append(accName).append("</td>");
    }
    body.append("</tr>");
    body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td></td>");
    for (int i = 0; i < accounts.size(); i++) {
        boolean first = true;
        for (Region region : regions) {
            body.append("<td style=\"font-weight: bold;padding: 4px;"
                    + (first ? "border-left: 1px solid #DDD;" : "") + "\">").append(region.name)
                    .append("</td>");
            first = false;
        }
    }
    body.append("<td style=\"border-left: 1px solid #DDD;\"></td></tr>");

    Map<String, Double> costs = Maps.newHashMap();

    Interval interval = new Interval(end.minusWeeks(numWeeks), end);
    double[] total = new double[numWeeks];
    for (Product product : products) {
        List<ResourceGroup> resourceGroups = getResourceGroups(appGroup, product);
        if (resourceGroups.size() == 0) {
            continue;
        }
        DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly);
        if (dataManager == null) {
            continue;
        }
        for (int i = 0; i < accounts.size(); i++) {
            List<Account> accountList = Lists.newArrayList(accounts.get(i));
            TagLists tagLists = new TagLists(accountList, regions, null, Lists.newArrayList(product), null,
                    null, resourceGroups);
            Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Region,
                    AggregateType.none, false);
            for (Tag tag : data.keySet()) {
                for (int week = 0; week < numWeeks; week++) {
                    String key = accounts.get(i) + "|" + tag + "|" + week;
                    if (costs.containsKey(key))
                        costs.put(key, data.get(tag)[week] + costs.get(key));
                    else
                        costs.put(key, data.get(tag)[week]);
                    total[week] += data.get(tag)[week];
                }
            }
        }
    }

    boolean firstLine = true;
    DateTime currentWeekEnd = end;
    for (int week = numWeeks - 1; week >= 0; week--) {
        String weekStr;
        if (week == numWeeks - 1)
            weekStr = "Last week";
        else
            weekStr = (numWeeks - week - 1) + " weeks ago";
        String background = week % 2 == 1 ? "background: whiteSmoke;" : "";
        body.append(String.format(
                "<tr style=\"%s\"><td nowrap style=\"border-left: 1px solid #DDD;padding: 4px\">%s (%s - %s)</td>",
                background, weekStr, formatter.print(currentWeekEnd.minusWeeks(1)).substring(5),
                formatter.print(currentWeekEnd).substring(5)));
        for (int i = 0; i < accounts.size(); i++) {
            Account account = accounts.get(i);
            for (int j = 0; j < regions.size(); j++) {
                Region region = regions.get(j);
                String key = account + "|" + region + "|" + week;
                double cost = costs.get(key) == null ? 0 : costs.get(key);
                Double lastCost = week == 0 ? null : costs.get(account + "|" + region + "|" + (week - 1));
                link = getLink("column", ConsolidateType.daily, appGroup, Lists.newArrayList(account),
                        Lists.newArrayList(region), currentWeekEnd.minusWeeks(1), currentWeekEnd);
                body.append(getValueCell(cost, lastCost, link, firstLine));
            }
        }
        link = getLink("column", ConsolidateType.daily, appGroup, accounts, regions,
                currentWeekEnd.minusWeeks(1), currentWeekEnd);
        body.append(getValueCell(total[week], week == 0 ? null : total[week - 1], link, firstLine));
        body.append("</tr>");
        firstLine = false;
        currentWeekEnd = currentWeekEnd.minusWeeks(1);
    }
    body.append("</table>");

    numberFormatter.setMaximumFractionDigits(0);
    numberFormatter.setMinimumFractionDigits(0);

    if (!StringUtils.isEmpty(throughputMetrics))
        body.append(throughputMetrics);

    body.append("<br><img src=\"cid:image_cid_" + index + "\"><br>");
    for (Map.Entry<String, List<String>> entry : appGroup.data.entrySet()) {
        String product = entry.getKey();
        List<String> selected = entry.getValue();
        if (selected == null || selected.size() == 0)
            continue;
        link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks),
                end);
        body.append(String.format("<b><h4>%s in <a href='%s'>%s</a>:</h4></b>",
                getResourceGroupsDisplayName(product), link, appGroup.getDisplayName()));
        for (String name : selected)
            body.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;").append(name).append("<br>");
    }
    body.append("<hr><br>");

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setFileName(file.getName());
    DataSource ds = new ByteArrayDataSource(new FileInputStream(file), "image/png");
    mimeBodyPart.setDataHandler(new DataHandler(ds));
    mimeBodyPart.setHeader("Content-ID", "<image_cid_" + index + ">");
    mimeBodyPart.setHeader("Content-Disposition", "inline");
    mimeBodyPart.setDisposition(MimeBodyPart.INLINE);

    file.delete();

    return mimeBodyPart;
}

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

/**
 * Creates an attachment containing the specified file.
 * /*from   w w w . j  a  v  a2s  .co m*/
 * @param fileNameWithPath the absolute file name
 */
public void addAttachmentFromFile(String fileNameWithPath) {
    try {
        File file = new File(fileNameWithPath);
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.attachFile(file);
        if (this.tempFileNameMappings.containsKey(fileNameWithPath)) {
            bodyPart.setFileName(this.tempFileNameMappings.get(fileNameWithPath));
        }
        this.attachments.add(bodyPart);
    } catch (IOException exception) {
        log.error("Error opening file " + fileNameWithPath, exception);
    } catch (MessagingException exception) {
        log.error("Error creating attachment comprising file " + fileNameWithPath);
    }

}

From source file:com.photon.phresco.util.Utility.java

public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body,
        String username, String password, String host, String screen, String build) throws PhrescoException {

    List<String> lists = Arrays.asList(toAddr);
    if (fromAddr == null) {
        fromAddr = "phresco.do.not.reply@gmail.com";
        username = "phresco.do.not.reply@gmail.com";
        password = "phresco123";
    }//ww  w.j a  v  a 2  s .co  m
    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.getDefaultInstance(props, new LoginAuthenticator(username, password));
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddr));
        List<Address> emailsList = getEmailsList(lists);
        Address[] dsf = new Address[emailsList.size()];
        message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf));
        message.setSubject(subject);
        DataSource source = new FileDataSource(body);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("Error.txt");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();
        DataSource source2 = new FileDataSource(screen);
        messageBodyPart2.setDataHandler(new DataHandler(source2));
        messageBodyPart2.setFileName("Error.jpg");
        multipart.addBodyPart(messageBodyPart2);
        MimeBodyPart mainPart = new MimeBodyPart();
        String content = "<b>Phresco framework error report<br><br>User Name:&nbsp;&nbsp;" + user
                + "<br> Email Address:&nbsp;&nbsp;" + fromAddr + "<br>Build No:&nbsp;&nbsp;" + build;
        mainPart.setContent(content, "text/html");
        multipart.addBodyPart(mainPart);
        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new PhrescoException(e);
    }
}