Example usage for org.apache.commons.mail HtmlEmail attach

List of usage examples for org.apache.commons.mail HtmlEmail attach

Introduction

In this page you can find the example usage for org.apache.commons.mail HtmlEmail attach.

Prototype

public MultiPartEmail attach(final File file) throws EmailException 

Source Link

Document

Attach a file.

Usage

From source file:com.mycollab.module.mail.DefaultMailer.java

@Override
public void sendHTMLMail(String fromEmail, String fromName, List<MailRecipientField> toEmails,
        List<MailRecipientField> ccEmails, List<MailRecipientField> bccEmails, String subject, String html,
        List<? extends AttachmentSource> attachments) {
    try {/*from ww  w  . j a  v a2 s  .c o m*/
        if (CollectionUtils.isEmpty(attachments)) {
            sendHTMLMail(fromEmail, fromName, toEmails, ccEmails, bccEmails, subject, html);
        } else {
            HtmlEmail email = getBasicEmail(fromEmail, fromName, toEmails, ccEmails, bccEmails, subject, html);

            for (AttachmentSource attachment : attachments) {
                email.attach(attachment.getAttachmentObj());
            }

            email.send();
        }
    } catch (EmailException e) {
        throw new MyCollabException(e);
    }
}

From source file:com.esofthead.mycollab.module.mail.DefaultMailer.java

@Override
public void sendHTMLMail(String fromEmail, String fromName, List<MailRecipientField> toEmail,
        List<MailRecipientField> ccEmail, List<MailRecipientField> bccEmail, String subject, String html,
        List<EmailAttachementSource> attachments) {
    try {//w  ww.jav a 2 s  . c  om
        if (CollectionUtils.isEmpty(attachments)) {
            sendHTMLMail(fromEmail, fromName, toEmail, ccEmail, bccEmail, subject, html);
        } else {
            HtmlEmail email = getBasicEmail(fromEmail, fromName, toEmail, ccEmail, bccEmail, subject, html);

            for (EmailAttachementSource attachment : attachments) {
                email.attach(attachment.getAttachmentObj());
            }

            email.send();
        }
    } catch (EmailException e) {
        throw new MyCollabException(e);
    }
}

From source file:com.smi.travel.util.Mail.java

public String sendmailwithAttchfile(String sendTo, String subject, String content, String attachfile,
        String sendCc) throws EmailException {
    String result = "";
    boolean send = false;
    EmailAttachment attachment = new EmailAttachment();
    HtmlEmail email = new HtmlEmail();
    try {// ww w  .j a va2 s .com
        if ((attachfile != null) && (!attachfile.equalsIgnoreCase(""))) {
            //attachment.setPath("C:\\Users\\Surachai\\Documents\\NetBeansProjects\\SMITravel\\test.txt");
            attachment.setPath(attachfile);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("file attachment");
            attachment.setName("text.txt");
            email.attach(attachment);
        }
        send = true;
    } catch (EmailException ex) {
        System.out.println("Email Exception");
        ex.printStackTrace();
        result = "fail";
    }
    if (send) {
        System.out.println(mail.getUsername() + mail.getPassword());
        email.setHostName(mail.getHostname());
        email.setSmtpPort(mail.getPort());
        email.setAuthentication(mail.getUsername(), mail.getPassword());
        email.setSSLOnConnect(true);
        email.setFrom(mail.getUsername());
        email.setSubject(subject);
        email.setHtmlMsg(content);
        String[] toSplit = sendTo.split("\\,");
        for (int i = 0; i < toSplit.length; i++) {
            System.out.println("Print toSplit" + toSplit[i]);
            email.addTo(toSplit[i]);
        }
        if (!sendCc.isEmpty()) {
            String[] ccSplit = sendCc.split("\\,");
            for (int i = 0; i < ccSplit.length; i++) {
                System.out.println("Print ccSplit" + ccSplit[i]);
                email.addCc(ccSplit[i]);
            }
        }
        email.send();

        result = "success";

    }
    return result;
}

From source file:edu.wright.cs.fa15.ceg3120.concon.server.EmailManager.java

/**
 * Add an outgoing email to the queue.// ww  w .jav  a2 s  .c o  m
 * @param to Array of email addresses.
 * @param subject Header
 * @param body Content
 * @param attachmentFile Attachment
 */
public void addEmail(String[] to, String subject, String body, File attachmentFile) {
    HtmlEmail mail = new HtmlEmail();
    Properties sysProps = System.getProperties();

    // Setup mail server
    sysProps.setProperty("mail.smtp.host", props.getProperty("mail_server_hostname"));
    Session session = Session.getDefaultInstance(sysProps);

    try {
        mail.setMailSession(session);
        mail.setFrom(props.getProperty("server_email_addr"), props.getProperty("server_title"));
        mail.addTo(to);
        mail.setSubject(subject);
        mail.setTextMsg(body);
        mail.setHtmlMsg(composeAsHtml(mail, body));
        if (attachmentFile.exists()) {
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(attachmentFile.getPath());
            mail.attach(attachment);
        }
    } catch (EmailException e) {
        LOG.warn("Email was not added. ", e);
    }
    mailQueue.add(mail);
}

From source file:com.manydesigns.mail.sender.DefaultMailSender.java

protected void send(Email emailBean) throws EmailException {
    logger.debug("Entering send(Email)");
    org.apache.commons.mail.Email email;
    String textBody = emailBean.getTextBody();
    String htmlBody = emailBean.getHtmlBody();
    if (null == htmlBody) {
        if (emailBean.getAttachments().isEmpty()) {
            SimpleEmail simpleEmail = new SimpleEmail();
            simpleEmail.setMsg(textBody);
            email = simpleEmail;//from ww  w .jav  a 2 s  .c om
        } else {
            MultiPartEmail multiPartEmail = new MultiPartEmail();
            multiPartEmail.setMsg(textBody);
            for (Attachment attachment : emailBean.getAttachments()) {
                EmailAttachment emailAttachment = new EmailAttachment();
                emailAttachment.setName(attachment.getName());
                emailAttachment.setDisposition(attachment.getDisposition());
                emailAttachment.setDescription(attachment.getDescription());
                emailAttachment.setPath(attachment.getFilePath());
                multiPartEmail.attach(emailAttachment);
            }
            email = multiPartEmail;
        }
    } else {
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setHtmlMsg(htmlBody);
        if (textBody != null) {
            htmlEmail.setTextMsg(textBody);
        }
        for (Attachment attachment : emailBean.getAttachments()) {
            if (!attachment.isEmbedded()) {
                EmailAttachment emailAttachment = new EmailAttachment();
                emailAttachment.setName(attachment.getName());
                emailAttachment.setDisposition(attachment.getDisposition());
                emailAttachment.setDescription(attachment.getDescription());
                emailAttachment.setPath(attachment.getFilePath());
                htmlEmail.attach(emailAttachment);
            } else {
                FileDataSource dataSource = new FileDataSource(new File(attachment.getFilePath()));
                htmlEmail.embed(dataSource, attachment.getName(), attachment.getContentId());
            }
        }
        email = htmlEmail;
    }

    if (null != login && null != password) {
        email.setAuthenticator(new DefaultAuthenticator(login, password));
    }
    email.setHostName(server);
    email.setSmtpPort(port);
    email.setSubject(emailBean.getSubject());
    email.setFrom(emailBean.getFrom());
    // hongliangpan add
    if ("smtp.163.com".equals(server)) {
        email.setFrom(login + "@163.com");
        // email.setAuthenticator(new DefaultAuthenticator("test28797575", "1qa2ws3ed"));
    }

    for (Recipient recipient : emailBean.getRecipients()) {
        switch (recipient.getType()) {
        case TO:
            email.addTo(recipient.getAddress());
            break;
        case CC:
            email.addCc(recipient.getAddress());
            break;
        case BCC:
            email.addBcc(recipient.getAddress());
            break;
        }
    }
    email.setSSL(ssl);
    email.setTLS(tls);
    email.setSslSmtpPort(port + "");
    email.setCharset("UTF-8");
    email.send();
    logger.debug("Exiting send(Email)");
}

From source file:com.vicky.common.utils.sendemail.SendEmailImpl.java

@Override
public void send(Mail mail) throws Exception {
    try {//w  w w.  j a v  a2s. c om
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setHostName(mail.getHost());
        htmlEmail.setCharset(Mail.ENCODEING);
        htmlEmail.addTo(mail.getReceiverEmailAddress());
        htmlEmail.setFrom(mail.getSenderEmailAddress(), mail.getName());
        htmlEmail.setAuthentication(mail.getSenderUsername(), mail.getSenderPassword());
        htmlEmail.setSubject(mail.getSubject());
        htmlEmail.setMsg(mail.getMessage());
        for (MailAttach mailFile : mail.getMailAttachs()) {
            EmailAttachment attachment = new EmailAttachment();//  
            attachment.setPath(mailFile.getFilePath());//?    
            //attachment.setURL(new URL("http://www.baidu.com/moumou"));//?  
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setName(MimeUtility.encodeText(mailFile.getFileName()));//??  
            htmlEmail.attach(attachment);//,?
        }
        htmlEmail.send();
    } catch (Exception exception) {
        exception.printStackTrace();
        this.logger.error("toString" + exception.toString());
        this.logger.error("getMessage" + exception.getMessage());
        this.logger.error("exception", exception);
        throw new StatusMsgException(
                "??,??,?,?V!");
    }
}

From source file:br.com.ezequieljuliano.argos.util.SendMail.java

public void send() throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(server.getHostName());
    email.setAuthentication(server.getUser(), server.getPassWord());
    email.setSSL(server.isSSL());/*from   w ww.j  a v a2  s.  c  o m*/
    email.setSmtpPort(server.getPort());

    for (Involved involved : recipients) {
        email.addTo(involved.getEmail(), involved.getName());
    }

    email.setFrom(sender.getEmail(), sender.getName());
    email.setSubject(subject);
    email.setHtmlMsg(message);
    email.setCharset("UTF-8");

    EmailAttachment att;
    for (Attachment annex : attachment) {
        att = new EmailAttachment();
        att.setPath(annex.getPath());
        att.setDisposition(EmailAttachment.ATTACHMENT);
        att.setDescription(annex.getDescription());
        att.setName(annex.getName());
        email.attach(att);
    }

    email.send();
}

From source file:de.maklerpoint.office.Schnittstellen.Email.MultiEmailSender.java

public void send() throws EmailException {

    if (files != null && urls != null) {
        attachments = new EmailAttachment[files.length + urls.length];

        int cnt = 0;

        for (int i = 0; i < files.length; i++) {
            attachments[cnt] = new EmailAttachment();
            attachments[cnt].setPath(files[i].getPath());
            attachments[cnt].setName(files[i].getName());
            attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT);

            cnt++;//from ww  w  . java  2  s . co  m
        }

        for (int i = 0; i < urls.length; i++) {
            attachments[cnt] = new EmailAttachment();
            attachments[cnt].setURL(urls[i]);
            attachments[cnt].setName(urls[i].getFile());
            attachments[cnt].setDisposition(EmailAttachment.ATTACHMENT);
            cnt++;
        }

    } else if (files != null) {
        attachments = new EmailAttachment[files.length];

        for (int i = 0; i < files.length; i++) {
            attachments[i] = new EmailAttachment();
            attachments[i].setPath(files[i].getPath());
            attachments[i].setName(files[i].getName());
            attachments[i].setDisposition(EmailAttachment.ATTACHMENT);
        }
    } else if (urls != null) {
        attachments = new EmailAttachment[urls.length];

        for (int i = 0; i < urls.length; i++) {
            attachments[i] = new EmailAttachment();
            attachments[i].setURL(urls[i]);
            attachments[i].setName(urls[i].getFile());
            attachments[i].setDisposition(EmailAttachment.ATTACHMENT);
        }
    }

    HtmlEmail email = new HtmlEmail();
    email.setHostName(Config.get("mailHost", ""));
    email.setSmtpPort(Config.getConfigInt("mailPort", 25));

    email.setTLS(Config.getConfigBoolean("mailTLS", false));
    email.setSSL(Config.getConfigBoolean("mailSSL", false));

    //email.setSslSmtpPort(Config.getConfigInt("emailPort", 25));
    email.setAuthenticator(
            new DefaultAuthenticator(Config.get("mailUsername", ""), Config.get("mailPassword", "")));

    email.setFrom(Config.get("mailSendermail", "info@example.de"), Config.get("mailSender", null));

    email.setSubject(subject);
    email.setHtmlMsg(body);
    email.setTextMsg(nohtmlmsg);

    for (int i = 0; i < adress.length; i++) {
        email.addTo(adress[i]);
    }

    if (cc != null) {
        for (int i = 0; i < cc.length; i++) {
            email.addCc(cc[i]);
        }
    }

    if (attachments != null) {
        for (int i = 0; i < attachments.length; i++) {
            email.attach(attachments[i]);
        }
    }

    email.send();

}

From source file:com.irurueta.server.commons.email.ApacheMailHtmlEmailMessage.java

/**
 * Builds email content to be sent using an email sender.
 * @param content instance where content must be set.
 * @throws com.irurueta.server.commons.email.EmailException if setting mail 
 * content fails.//from w ww.  j a  v a2s . c o m
 */
@Override
protected void buildContent(HtmlEmail content) throws com.irurueta.server.commons.email.EmailException {
    try {
        if (getAlternativeText() != null) {
            content.setTextMsg(getAlternativeText());
        }

        //process inline attachments
        boolean[] generated = processInlineAttachments();

        if (getHtmlContent() != null) {
            content.setHtmlMsg(process(getHtmlContent(), generated));
        }

        //all attachments go into general message multipar

        //add inline attachments
        List<InlineAttachment> inlineAttachments = getInlineAttachments();
        if (inlineAttachments != null) {
            for (InlineAttachment attachment : inlineAttachments) {
                //only add attachments with files and content ids
                if (attachment.getContentId() == null || attachment.getAttachment() == null) {
                    continue;
                }

                content.embed(attachment.getAttachment(), attachment.getContentId());
            }
        }

        //add other attachments parts
        List<EmailAttachment> attachments = getEmailAttachments();
        org.apache.commons.mail.EmailAttachment apacheAttachment;
        if (attachments != null) {
            for (EmailAttachment attachment : attachments) {
                //only add attachments with files
                if (attachment.getAttachment() == null) {
                    continue;
                }

                apacheAttachment = new org.apache.commons.mail.EmailAttachment();
                apacheAttachment.setPath(attachment.getAttachment().getAbsolutePath());
                apacheAttachment.setDisposition(org.apache.commons.mail.EmailAttachment.ATTACHMENT);
                if (attachment.getName() != null) {
                    apacheAttachment.setName(attachment.getName());
                }

                content.attach(apacheAttachment);
            }
        }
    } catch (EmailException e) {
        throw new com.irurueta.server.commons.email.EmailException(e);
    }
}

From source file:com.jnd.sonar.analysisreport.AnalysisReportHelper.java

private void sendEmail(String reportname, Map<String, String> reportDataMap2) {
    try {//from  w  w  w .  j  a v a  2s  . com

        // Create the email message
        //MultiPartEmail email = new MultiPartEmail();   
        StringBuilder strHtmlContentSummary = new StringBuilder();
        System.out.println("Analysis -  Sonar Email Notification");
        from = settings.getString("sonar.jd.smptp.username");
        System.out.println("from=>" + from);
        to_email = settings.getString("sonar.jd.smptp.to");
        System.out.println("to_email=>" + to_email);

        to_email_name = settings.getString("sonar.jd.smptp.to_name");
        System.out.println("to_email_name=>" + to_email_name);

        username = settings.getString("sonar.jd.smptp.username");
        System.out.println("username=>" + username);
        password = settings.getString("sonar.jd.smptp.password");
        System.out.println("password=>" + password);
        hostname = settings.getString("sonar.jd.smptp.host");
        System.out.println("hostname=>" + hostname);
        portno = settings.getString("sonar.jd.smptp.sslport");
        System.out.println("portno=>" + portno);
        setSSLOnConnectFlag = settings.getBoolean("sonar.jd.smptp.set_ssl_on_connect");
        System.out.println("setSSLOnConnectFlag=>" + String.valueOf(setSSLOnConnectFlag));
        subject = settings.getString("sonar.jd.smptp.subject");
        System.out.println("subject=>" + subject);
        message = settings.getString("sonar.jd.smptp.message");
        System.out.println("message=>" + message);

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName(hostname);
        email.setSslSmtpPort(portno);
        if (!StringUtils.isBlank(username) || !StringUtils.isBlank(password)) {
            email.setAuthentication(username, password);
        }
        //email.setSSLOnConnect(setSSLOnConnectFlag);
        email.setSSL(setSSLOnConnectFlag);
        String[] addrs = StringUtils.split(to_email, "\t\r\n;, ");
        for (String addr : addrs) {
            email.addTo(addr);
        }
        //email.addTo(to_email,to_email_name);
        email.setFrom(from);
        email.setSubject(subject);
        //email.setMsg(message);

        // embed the image and get the content id   
        URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
        String cid = email.embed(url, "Apache logo - 1");

        System.out.println("Print Entries from Analysis Data Map.");
        int i = 1;
        strHtmlContentSummary.append("<html><body>The apache logo - <img src=\"cid:" + cid
                + "\"><br><br><br><b><center>Metric Information:-</center></b><br><table border='2'>");
        for (Map.Entry<String, String> entry : reportDataMap.entrySet()) {
            strHtmlContentSummary
                    .append("<tr><td>" + entry.getKey() + ":</td><td>" + entry.getValue() + "</td></tr>");
            i++;
        }
        strHtmlContentSummary.append("</table></body></html>");
        System.out.println(strHtmlContentSummary.toString());
        // set the html message
        email.setHtmlMsg(strHtmlContentSummary.toString());
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // Create the attachment
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(reportname);

        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Sonar Analysis Report" + reportname);
        attachment.setName(reportname);
        email.attach(attachment);
        // send the email
        System.out.println("Sending the Email");
        email.send();
    } catch (EmailException e) {
        throw new SonarException("Unable to send email", e);
    } catch (Exception ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

}