Search in sources :

Example 6 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail in project ninja by ninjaframework.

the class CommonsMailHelperImplTest method testCreateMultiPartEmailWithContent.

@Test
public void testCreateMultiPartEmailWithContent() throws Exception {
    // /////////////////////////////////////////////////////////////////////
    // Test with text only content
    // /////////////////////////////////////////////////////////////////////
    Mail mail = new MailImpl();
    // set only text:
    mail.setBodyText("simple body text");
    MultiPartEmail multiPartEmail = commonsmailHelper.createMultiPartEmailWithContent(mail);
    assertTrue(multiPartEmail instanceof MultiPartEmail);
    // /////////////////////////////////////////////////////////////////////
    // Test with html only content
    // /////////////////////////////////////////////////////////////////////
    mail = new MailImpl();
    // set only text:
    mail.setBodyHtml("<br>simple body text<br>");
    multiPartEmail = commonsmailHelper.createMultiPartEmailWithContent(mail);
    assertTrue(multiPartEmail instanceof HtmlEmail);
    // /////////////////////////////////////////////////////////////////////
    // Test with html AND text content
    // /////////////////////////////////////////////////////////////////////
    mail = new MailImpl();
    // set only text:
    mail.setBodyText("simple body text");
    mail.setBodyHtml("<br>simple body text<br>");
    multiPartEmail = commonsmailHelper.createMultiPartEmailWithContent(mail);
    assertTrue(multiPartEmail instanceof HtmlEmail);
}
Also used : Mail(ninja.postoffice.Mail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) HtmlEmail(org.apache.commons.mail.HtmlEmail) MailImpl(ninja.postoffice.common.MailImpl) Test(org.junit.Test)

Example 7 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail in project ninja by ninjaframework.

the class CommonsMailHelperImplTest method testDoSetServerParameter.

@Test
public void testDoSetServerParameter() throws Exception {
    Mail mail = MailImplTestHelper.getMailImplWithDemoContent();
    MultiPartEmail multiPartEmail = commonsmailHelper.createMultiPartEmailWithContent(mail);
    commonsmailHelper.doSetServerParameter(multiPartEmail, "mail.superserver.com", 33, true, false, false, "username", "password", true);
    assertEquals("33", multiPartEmail.getSmtpPort());
    assertEquals("mail.superserver.com", multiPartEmail.getHostName());
    assertEquals(true, multiPartEmail.getMailSession().getDebug());
}
Also used : Mail(ninja.postoffice.Mail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) Test(org.junit.Test)

Example 8 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail in project Japid by branaway.

the class JapidMailer method send.

@SuppressWarnings("unchecked")
public static Future<Boolean> send(Object... args) {
    try {
        final HashMap<String, Object> infoMap = getInfoMap();
        // Body character set
        final String charset = (String) infoMap.get(CHARSET);
        // Headers
        final Map<String, String> headers = (Map<String, String>) infoMap.get(HEADERS);
        // Subject
        final String subject = (String) infoMap.get(SUBJECT);
        // xxx how to determine the method name???
        // String templateName = (String) infoMap.get(METHOD);
        String templateNameBase = StackTraceUtils.getCaller();
        if (!templateNameBase.startsWith("notifiers")) {
            throw new RuntimeException("The emailers must be put in the \"notifiers\" package.");
        }
        // if (templateNameBase.startsWith(NOTIFIERS)) {
        // templateNameBase = templateNameBase.substring(NOTIFIERS.length());
        // }
        // if (templateNameBase.startsWith(CONTROLLERS)) {
        // templateNameBase = templateNameBase.substring(CONTROLLERS.length());
        // }
        // templateNameBase = templateNameBase.substring(0, templateNameBase.indexOf("("));
        // templateNameBase = templateNameBase.replace(".", "/");
        // final Map<String, Object> templateHtmlBinding = new HashMap<String, Object>();
        // final Map<String, Object> templateTextBinding = new HashMap<String, Object>();
        // for (Object o : args) {
        // List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o);
        // for (String name : names) {
        // templateHtmlBinding.put(name, o);
        // templateTextBinding.put(name, o);
        // }
        // }
        String templateClassName = DirUtil.JAPIDVIEWS_ROOT + "._" + templateNameBase;
        String bodyHtml = null;
        Class tClass = Play.classloader.getClassIgnoreCase(templateClassName);
        if (tClass == null) {
            String templateFileName = templateClassName.replace('.', '/') + ".html";
            throw new RuntimeException("Japid Emailer: could not find a Japid template with the name of: " + templateFileName);
        } else if (JapidTemplateBase.class.isAssignableFrom(tClass)) {
            try {
                JapidController.render(tClass, args);
            } catch (JapidResult jr) {
                RenderResult rr = jr.getRenderResult();
                bodyHtml = rr.getContent().toString();
            }
        } else {
            throw new RuntimeException("The found class is not a Japid template class: " + templateClassName);
        }
        // System.out.println("email body: " + bodyHtml);
        // The rule is as follow: If we ask for text/plain, we don't care about the HTML
        // If we ask for HTML and there is a text/plain we add it as an alternative.
        // If contentType is not specified look at the template available:
        // - .txt only -> text/plain
        // else
        // -           -> text/html
        // String contentType = (String) infoMap.get(CONTENT_TYPE);
        // String bodyText = "";
        // try {
        // Template templateHtml = TemplateLoader.load(templateNameBase + ".html");
        // bodyHtml = templateHtml.render(templateHtmlBinding);
        // } catch (TemplateNotFoundException e) {
        // if (contentType != null && !contentType.startsWith(TEXT_PLAIN)) {
        // throw e;
        // }
        // }
        // //
        // try {
        // Template templateText = TemplateLoader.load(templateName + ".txt");
        // bodyText = templateText.render(templateTextBinding);
        // } catch (TemplateNotFoundException e) {
        // if (bodyHtml == null && (contentType == null || contentType.startsWith(TEXT_PLAIN))) {
        // throw e;
        // }
        // }
        // Content type
        // bran html for now
        // if (contentType == null) {
        // if (bodyHtml != null) {
        // contentType = TEXT_HTML;
        // } else {
        // contentType = TEXT_PLAIN;
        // }
        // }
        // Recipients
        final List<Object> recipientList = (List<Object>) infoMap.get(RECIPIENTS);
        // From
        final Object from = infoMap.get(FROM);
        final Object replyTo = infoMap.get(REPLY_TO);
        Email email = null;
        if (infoMap.get(ATTACHMENTS) == null) {
            // if (StringUtils.isEmpty(bodyHtml)) {
            // email = new SimpleEmail();
            // email.setMsg(bodyText);
            // } else {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setHtmlMsg(bodyHtml);
            // if (!StringUtils.isEmpty(bodyText)) {
            // htmlEmail.setTextMsg(bodyText);
            // }
            email = htmlEmail;
        // }
        } else {
            // if (StringUtils.isEmpty(bodyHtml)) {
            // email = new MultiPartEmail();
            // email.setMsg(bodyText);
            // } else {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setHtmlMsg(bodyHtml);
            // if (!StringUtils.isEmpty(bodyText)) {
            // htmlEmail.setTextMsg(bodyText);
            // }
            email = htmlEmail;
            // }
            MultiPartEmail multiPartEmail = (MultiPartEmail) email;
            List<EmailAttachment> objectList = (List<EmailAttachment>) infoMap.get(ATTACHMENTS);
            for (EmailAttachment object : objectList) {
                multiPartEmail.attach(object);
            }
        }
        if (from != null) {
            try {
                InternetAddress iAddress = new InternetAddress(from.toString());
                email.setFrom(iAddress.getAddress(), iAddress.getPersonal());
            } catch (Exception e) {
                email.setFrom(from.toString());
            }
        }
        if (replyTo != null) {
            try {
                InternetAddress iAddress = new InternetAddress(replyTo.toString());
                email.addReplyTo(iAddress.getAddress(), iAddress.getPersonal());
            } catch (Exception e) {
                email.addReplyTo(replyTo.toString());
            }
        }
        if (recipientList != null) {
            for (Object recipient : recipientList) {
                try {
                    InternetAddress iAddress = new InternetAddress(recipient.toString());
                    email.addTo(iAddress.getAddress(), iAddress.getPersonal());
                } catch (Exception e) {
                    email.addTo(recipient.toString());
                }
            }
        } else {
            throw new MailException("You must specify at least one recipient.");
        }
        List<Object> ccsList = (List<Object>) infoMap.get(CCS);
        if (ccsList != null) {
            for (Object cc : ccsList) {
                email.addCc(cc.toString());
            }
        }
        List<Object> bccsList = (List<Object>) infoMap.get(BCCS);
        if (bccsList != null) {
            for (Object bcc : bccsList) {
                try {
                    InternetAddress iAddress = new InternetAddress(bcc.toString());
                    email.addBcc(iAddress.getAddress(), iAddress.getPersonal());
                } catch (Exception e) {
                    email.addBcc(bcc.toString());
                }
            }
        }
        if (!StringUtils.isEmpty(charset)) {
            email.setCharset(charset);
        }
        email.setSubject(subject);
        email.updateContentType(TEXT_HTML);
        if (headers != null) {
            for (String key : headers.keySet()) {
                email.addHeader(key, headers.get(key));
            }
        }
        // reset the infomap
        infos.remove();
        return Mail.send(email);
    } catch (EmailException ex) {
        throw new MailException("Cannot send email", ex);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Email(org.apache.commons.mail.Email) HtmlEmail(org.apache.commons.mail.HtmlEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) EmailAttachment(org.apache.commons.mail.EmailAttachment) RenderResult(cn.bran.japid.template.RenderResult) HtmlEmail(org.apache.commons.mail.HtmlEmail) MailException(play.exceptions.MailException) ExecutionException(java.util.concurrent.ExecutionException) UnexpectedException(play.exceptions.UnexpectedException) EmailException(org.apache.commons.mail.EmailException) EmailException(org.apache.commons.mail.EmailException) ArrayList(java.util.ArrayList) List(java.util.List) MailException(play.exceptions.MailException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 9 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail in project SpringStepByStep by JavaProgrammerLB.

the class JavaMailDemo method sendEmailWithAttachment.

// @Test
public void sendEmailWithAttachment() {
    try {
        // Create the attachment
        EmailAttachment attachment = new EmailAttachment();
        System.out.println(System.getProperty("user.dir"));
        attachment.setPath("src/main/resources/john.jpg");
        // 通过url添加附件			  attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Picture of John");
        attachment.setName("John.jpg");
        // Create the email message
        MultiPartEmail email = new MultiPartEmail();
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        email.setSSLOnConnect(true);
        email.setFrom("username", "LIUBEI");
        email.addTo("admin@yitianyigexiangfa.com", "ADMIN");
        email.setAuthentication("username", "password");
        email.setSubject("The picture");
        email.setMsg("Here is the picture you wanted");
        // add the attachment
        email.attach(attachment);
        // send the email
        email.send();
        System.out.println("finished!!!");
    } catch (EmailException e) {
        e.printStackTrace();
    }
}
Also used : EmailAttachment(org.apache.commons.mail.EmailAttachment) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) EmailException(org.apache.commons.mail.EmailException)

Example 10 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail in project nifi by apache.

the class ConsumeEWS method parseMessage.

public MimeMessage parseMessage(EmailMessage item, List<String> hdrIncludeList, List<String> hdrExcludeList) throws Exception {
    EmailMessage ewsMessage = item;
    final String bodyText = ewsMessage.getBody().toString();
    MultiPartEmail mm;
    if (ewsMessage.getBody().getBodyType() == BodyType.HTML) {
        mm = new HtmlEmail().setHtmlMsg(bodyText);
    } else {
        mm = new MultiPartEmail();
        mm.setMsg(bodyText);
    }
    mm.setHostName("NiFi-EWS");
    // from
    mm.setFrom(ewsMessage.getFrom().getAddress());
    // to recipients
    ewsMessage.getToRecipients().forEach(x -> {
        try {
            mm.addTo(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add TO recipient.", e);
        }
    });
    // cc recipients
    ewsMessage.getCcRecipients().forEach(x -> {
        try {
            mm.addCc(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add CC recipient.", e);
        }
    });
    // subject
    mm.setSubject(ewsMessage.getSubject());
    // sent date
    mm.setSentDate(ewsMessage.getDateTimeSent());
    // add message headers
    ewsMessage.getInternetMessageHeaders().getItems().stream().filter(x -> (hdrIncludeList == null || hdrIncludeList.isEmpty() || hdrIncludeList.contains(x.getName())) && (hdrExcludeList == null || hdrExcludeList.isEmpty() || !hdrExcludeList.contains(x.getName()))).forEach(x -> mm.addHeader(x.getName(), x.getValue()));
    // Any attachments
    if (ewsMessage.getHasAttachments()) {
        ewsMessage.getAttachments().forEach(x -> {
            try {
                FileAttachment file = (FileAttachment) x;
                file.load();
                ByteArrayDataSource bds = new ByteArrayDataSource(file.getContent(), file.getContentType());
                mm.attach(bds, file.getName(), "", EmailAttachment.ATTACHMENT);
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
    mm.buildMimeMessage();
    return mm.getMimeMessage();
}
Also used : OutputStreamCallback(org.apache.nifi.processor.io.OutputStreamCallback) StandardValidators(org.apache.nifi.processor.util.StandardValidators) Message(javax.mail.Message) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Arrays(java.util.Arrays) URISyntaxException(java.net.URISyntaxException) FindItemsResults(microsoft.exchange.webservices.data.search.FindItemsResults) LoggerFactory(org.slf4j.LoggerFactory) FolderTraversal(microsoft.exchange.webservices.data.core.enumeration.search.FolderTraversal) MessagingException(javax.mail.MessagingException) StringUtils(org.apache.commons.lang3.StringUtils) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) EmailMessageSchema(microsoft.exchange.webservices.data.core.service.schema.EmailMessageSchema) FolderSchema(microsoft.exchange.webservices.data.core.service.schema.FolderSchema) PropertySet(microsoft.exchange.webservices.data.core.PropertySet) IAutodiscoverRedirectionUrl(microsoft.exchange.webservices.data.autodiscover.IAutodiscoverRedirectionUrl) URI(java.net.URI) BodyType(microsoft.exchange.webservices.data.core.enumeration.property.BodyType) FlowFile(org.apache.nifi.flowfile.FlowFile) ExchangeService(microsoft.exchange.webservices.data.core.ExchangeService) DeleteMode(microsoft.exchange.webservices.data.core.enumeration.service.DeleteMode) ExchangeVersion(microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) FolderView(microsoft.exchange.webservices.data.search.FolderView) ItemSchema(microsoft.exchange.webservices.data.core.service.schema.ItemSchema) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) SortDirection(microsoft.exchange.webservices.data.core.enumeration.search.SortDirection) InputRequirement(org.apache.nifi.annotation.behavior.InputRequirement) List(java.util.List) ConflictResolutionMode(microsoft.exchange.webservices.data.core.enumeration.service.ConflictResolutionMode) EmailException(org.apache.commons.mail.EmailException) Tags(org.apache.nifi.annotation.documentation.Tags) FileAttachment(microsoft.exchange.webservices.data.property.complex.FileAttachment) ExchangeCredentials(microsoft.exchange.webservices.data.credential.ExchangeCredentials) Address(javax.mail.Address) SearchFilter(microsoft.exchange.webservices.data.search.filter.SearchFilter) CapabilityDescription(org.apache.nifi.annotation.documentation.CapabilityDescription) EmailMessage(microsoft.exchange.webservices.data.core.service.item.EmailMessage) HtmlEmail(org.apache.commons.mail.HtmlEmail) Flags(javax.mail.Flags) ProcessException(org.apache.nifi.processor.exception.ProcessException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) EmailAttachment(org.apache.commons.mail.EmailAttachment) Relationship(org.apache.nifi.processor.Relationship) LogicalOperator(microsoft.exchange.webservices.data.core.enumeration.search.LogicalOperator) OutputStream(java.io.OutputStream) WellKnownFolderName(microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName) Logger(org.slf4j.Logger) Validator(org.apache.nifi.components.Validator) ItemView(microsoft.exchange.webservices.data.search.ItemView) ProcessContext(org.apache.nifi.processor.ProcessContext) ProcessSession(org.apache.nifi.processor.ProcessSession) IOException(java.io.IOException) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) MimeMessage(javax.mail.internet.MimeMessage) TimeUnit(java.util.concurrent.TimeUnit) Item(microsoft.exchange.webservices.data.core.service.item.Item) WebCredentials(microsoft.exchange.webservices.data.credential.WebCredentials) FindFoldersResults(microsoft.exchange.webservices.data.search.FindFoldersResults) AbstractProcessor(org.apache.nifi.processor.AbstractProcessor) Folder(microsoft.exchange.webservices.data.core.service.folder.Folder) OnStopped(org.apache.nifi.annotation.lifecycle.OnStopped) EmailMessage(microsoft.exchange.webservices.data.core.service.item.EmailMessage) ProcessException(org.apache.nifi.processor.exception.ProcessException) MessagingException(javax.mail.MessagingException) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) FileAttachment(microsoft.exchange.webservices.data.property.complex.FileAttachment) HtmlEmail(org.apache.commons.mail.HtmlEmail) EmailException(org.apache.commons.mail.EmailException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) URISyntaxException(java.net.URISyntaxException) MessagingException(javax.mail.MessagingException) EmailException(org.apache.commons.mail.EmailException) ProcessException(org.apache.nifi.processor.exception.ProcessException) IOException(java.io.IOException)

Aggregations

MultiPartEmail (org.apache.commons.mail.MultiPartEmail)22 EmailException (org.apache.commons.mail.EmailException)11 EmailAttachment (org.apache.commons.mail.EmailAttachment)9 HtmlEmail (org.apache.commons.mail.HtmlEmail)6 ArrayList (java.util.ArrayList)4 List (java.util.List)4 InternetAddress (javax.mail.internet.InternetAddress)4 Email (org.apache.commons.mail.Email)4 RenderResult (cn.bran.japid.template.RenderResult)3 IOException (java.io.IOException)3 URL (java.net.URL)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ExecutionException (java.util.concurrent.ExecutionException)3 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)3 Mail (ninja.postoffice.Mail)3 Test (org.junit.Test)3 MessagingException (javax.mail.MessagingException)2 MimeMessage (javax.mail.internet.MimeMessage)2 MailException (cn.bran.play.exceptions.MailException)1