Search in sources :

Example 31 with HtmlEmail

use of org.apache.commons.mail.HtmlEmail in project meteo by pierre.

the class AlertListener method createAndSendAlertEmail.

private void createAndSendAlertEmail(String body) {
    try {
        log.info(String.format("Sending alert email to [%s]: %s", config.getRecipients(), body));
        HtmlEmail email = new HtmlEmail();
        email.setTextMsg(body);
        email.setFrom("esper-is-awesome@example.com");
        email.setTo(Arrays.asList(new InternetAddress(config.getRecipients())));
        email.setHostName(config.getHost());
        email.setSmtpPort(config.getPort());
        email.send();
    } catch (Exception ex) {
        log.warn("Could not create or send email", ex);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) HtmlEmail(org.apache.commons.mail.HtmlEmail)

Example 32 with HtmlEmail

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

the class JavaMailDemo method sendEmailWithHtml.

//	@Test
public void sendEmailWithHtml() {
    try {
        // Create the email message
        HtmlEmail email = new HtmlEmail();
        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");
        // 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");
        // set the html message
        email.setHtmlMsg("<html>The apache logo - <img src=\"cid:" + cid + "\"></html>");
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");
        // send the email
        email.send();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (EmailException e) {
        e.printStackTrace();
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) ImageHtmlEmail(org.apache.commons.mail.ImageHtmlEmail) HtmlEmail(org.apache.commons.mail.HtmlEmail) EmailException(org.apache.commons.mail.EmailException) URL(java.net.URL)

Example 33 with HtmlEmail

use of org.apache.commons.mail.HtmlEmail 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)

Example 34 with HtmlEmail

use of org.apache.commons.mail.HtmlEmail in project dal by ctripcorp.

the class GenTaskResource method taskApproveOperationForEmail.

@GET
@Path("taskApproveOperationForEmail")
@Produces(MediaType.APPLICATION_JSON)
public String taskApproveOperationForEmail(@Context HttpServletRequest request, @QueryParam("taskId") int taskId, @QueryParam("taskType") String taskType, @QueryParam("approveFlag") int approveFlag, @QueryParam("approveMsg") String approveMsg) throws Exception {
    try {
        String userNo = RequestUtil.getUserNo(request);
        LoginUser user = BeanGetter.getDaoOfLoginUser().getUserByNo(userNo);
        if (user == null) {
            return "please login fisrt.";
        }
        ApproveTask task = haveApprovePermision(user.getId(), taskId, taskType);
        if (task == null) {
            return "Dao have been approved.";
        }
        List<GenTaskByTableViewSp> tableViewSpTasks = new ArrayList<>();
        List<GenTaskBySqlBuilder> autoTasks = new ArrayList<>();
        List<GenTaskByFreeSql> sqlTasks = new ArrayList<>();
        if ("table_view_sp".equalsIgnoreCase(taskType)) {
            BeanGetter.getDaoByTableViewSp().updateTask(taskId, approveFlag, approveMsg);
            BeanGetter.getApproveTaskDao().deleteApproveTaskByTaskIdAndType(taskId, taskType);
            tableViewSpTasks.add(BeanGetter.getDaoByTableViewSp().getTasksByTaskId(taskId));
        } else if ("auto".equalsIgnoreCase(taskType)) {
            BeanGetter.getDaoBySqlBuilder().updateTask(taskId, approveFlag, approveMsg);
            BeanGetter.getApproveTaskDao().deleteApproveTaskByTaskIdAndType(taskId, taskType);
            autoTasks.add(BeanGetter.getDaoBySqlBuilder().getTasksByTaskId(taskId));
        } else if ("sql".equalsIgnoreCase(taskType)) {
            BeanGetter.getDaoByFreeSql().updateTask(taskId, approveFlag, approveMsg);
            BeanGetter.getApproveTaskDao().deleteApproveTaskByTaskIdAndType(taskId, taskType);
            sqlTasks.add(BeanGetter.getDaoByFreeSql().getTasksByTaskId(taskId));
        }
        java.util.Collections.sort(tableViewSpTasks);
        java.util.Collections.sort(autoTasks);
        java.util.Collections.sort(sqlTasks);
        LoginUser noticeUsr = BeanGetter.getDaoOfLoginUser().getUserById(task.getCreate_user_id());
        VelocityContext context = GenUtils.buildDefaultVelocityContext();
        context.put("standardDao", tableViewSpTasks);
        context.put("autoDao", autoTasks);
        context.put("sqlDao", sqlTasks);
        String msg = "你好," + noticeUsr.getUserName() + ":<br/>&nbsp;&nbsp;你提交的DAO已审批,审批";
        if (approveFlag == 2) {
            msg += "通过。";
        } else {
            msg += "未通过。";
        }
        if (approveMsg != null) {
            msg += "<br/>&nbsp;&nbsp;审批意见:" + approveMsg;
        }
        context.put("msg", msg);
        String mailMsg = GenUtils.mergeVelocityContext(context, "templates/approval/approveResult.tpl");
        HtmlEmail email = new HtmlEmail();
        email.setHostName(Configuration.get("email_host_name"));
        email.setAuthentication(Configuration.get("email_user_name"), Configuration.get("email_password"));
        try {
            email.addTo(noticeUsr.getUserEmail());
            email.setFrom(user.getUserEmail(), user.getUserName());
            email.setSubject("Codegen DAO 审批结果通知");
            email.setHtmlMsg(mailMsg);
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }
        return "Success Approved.";
    } catch (Throwable e) {
        LoggerManager.getInstance().error(e);
        throw e;
    }
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) HtmlEmail(org.apache.commons.mail.HtmlEmail) EmailException(org.apache.commons.mail.EmailException)

Example 35 with HtmlEmail

use of org.apache.commons.mail.HtmlEmail in project xxl-job by xuxueli.

the class MailUtil method sendMail.

/**
 * @param toAddress		收件人邮箱
 * @param mailSubject	邮件主题
 * @param mailBody		邮件正文
 * @return
 */
public static boolean sendMail(String toAddress, String mailSubject, String mailBody) {
    try {
        // Create the email message
        HtmlEmail email = new HtmlEmail();
        // email.setDebug(true);		// 将会打印一些log
        // email.setTLS(true);		// 是否TLS校验,,某些邮箱需要TLS安全校验,同理有SSL校验
        // email.setSSL(true);
        email.setHostName(XxlJobAdminConfig.getAdminConfig().getMailHost());
        email.setSmtpPort(Integer.valueOf(XxlJobAdminConfig.getAdminConfig().getMailPort()));
        // email.setSslSmtpPort(port);
        email.setAuthenticator(new DefaultAuthenticator(XxlJobAdminConfig.getAdminConfig().getMailUsername(), XxlJobAdminConfig.getAdminConfig().getMailPassword()));
        email.setCharset(Charset.defaultCharset().name());
        email.setFrom(XxlJobAdminConfig.getAdminConfig().getMailUsername(), XxlJobAdminConfig.getAdminConfig().getMailSendNick());
        email.addTo(toAddress);
        email.setSubject(mailSubject);
        email.setMsg(mailBody);
        // email.attach(attachment);	// add the attachment
        // send the email
        email.send();
        return true;
    } catch (EmailException e) {
        logger.error(e.getMessage(), e);
    }
    return false;
}
Also used : HtmlEmail(org.apache.commons.mail.HtmlEmail) EmailException(org.apache.commons.mail.EmailException) DefaultAuthenticator(org.apache.commons.mail.DefaultAuthenticator)

Aggregations

HtmlEmail (org.apache.commons.mail.HtmlEmail)47 EmailException (org.apache.commons.mail.EmailException)24 Test (org.junit.Test)10 ArrayList (java.util.ArrayList)8 HashMap (java.util.HashMap)7 Email (org.apache.commons.mail.Email)7 MultiPartEmail (org.apache.commons.mail.MultiPartEmail)6 IOException (java.io.IOException)5 InternetAddress (javax.mail.internet.InternetAddress)5 DefaultAuthenticator (org.apache.commons.mail.DefaultAuthenticator)5 Configuration (freemarker.template.Configuration)4 Template (freemarker.template.Template)4 File (java.io.File)4 List (java.util.List)4 Map (java.util.Map)4 EmailAttachment (org.apache.commons.mail.EmailAttachment)4 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)4 JobExecutionException (org.quartz.JobExecutionException)4 RenderResult (cn.bran.japid.template.RenderResult)3 ThirdEyeAnomalyConfiguration (com.linkedin.thirdeye.anomaly.ThirdEyeAnomalyConfiguration)3