Search in sources :

Example 1 with HtmlEmail

use of org.apache.commons.mail.HtmlEmail in project pinot by linkedin.

the class AlertTaskRunner method sendFailureEmail.

private void sendFailureEmail(Throwable t) throws JobExecutionException {
    HtmlEmail email = new HtmlEmail();
    String collection = alertConfig.getCollection();
    String metric = alertConfig.getMetric();
    String subject = String.format("[ThirdEye Anomaly Detector] FAILED ALERT ID=%d (%s:%s)", alertConfig.getId(), collection, metric);
    String textBody = String.format("%s%n%nException:%s", alertConfig.toString(), ExceptionUtils.getStackTrace(t));
    try {
        EmailHelper.sendEmailWithTextBody(email, thirdeyeConfig.getSmtpConfiguration(), subject, textBody, thirdeyeConfig.getFailureFromAddress(), thirdeyeConfig.getFailureToAddress());
    } catch (EmailException e) {
        throw new JobExecutionException(e);
    }
}
Also used : JobExecutionException(org.quartz.JobExecutionException) HtmlEmail(org.apache.commons.mail.HtmlEmail) EmailException(org.apache.commons.mail.EmailException)

Example 2 with HtmlEmail

use of org.apache.commons.mail.HtmlEmail in project pinot by linkedin.

the class AnomalyReportGenerator method buildReport.

public void buildReport(long startTime, long endTime, List<MergedAnomalyResultDTO> anomalies, String subject, ThirdEyeAnomalyConfiguration configuration, boolean includeSentAnomaliesOnly, String emailRecipients, String fromEmail, String alertConfigName, boolean includeSummary) {
    if (anomalies == null || anomalies.size() == 0) {
        LOG.info("No anomalies found to send email, please check the parameters.. exiting");
    } else {
        Set<String> metrics = new HashSet<>();
        int alertedAnomalies = 0;
        int feedbackCollected = 0;
        int trueAlert = 0;
        int falseAlert = 0;
        int nonActionable = 0;
        List<AnomalyReportDTO> anomalyReportDTOList = new ArrayList<>();
        List<String> anomalyIds = new ArrayList<>();
        for (MergedAnomalyResultDTO anomaly : anomalies) {
            metrics.add(anomaly.getMetric());
            if (anomaly.getFeedback() != null) {
                feedbackCollected++;
                if (anomaly.getFeedback().getFeedbackType().equals(AnomalyFeedbackType.ANOMALY)) {
                    trueAlert++;
                } else if (anomaly.getFeedback().getFeedbackType().equals(AnomalyFeedbackType.NOT_ANOMALY)) {
                    falseAlert++;
                } else {
                    nonActionable++;
                }
            }
            String feedbackVal = getFeedback(anomaly.getFeedback() == null ? "Not Resolved" : "Resolved(" + anomaly.getFeedback().getFeedbackType().name() + ")");
            DateTimeZone dateTimeZone = Utils.getDataTimeZone(anomaly.getCollection());
            AnomalyReportDTO anomalyReportDTO = new AnomalyReportDTO(String.valueOf(anomaly.getId()), getAnomalyURL(anomaly, configuration.getDashboardHost()), String.format("%.2f", anomaly.getAvgBaselineVal()), String.format("%.2f", anomaly.getAvgCurrentVal()), getDimensionsString(anomaly.getDimensions()), String.format("%.2f hours (%s to %s) %s", getTimeDiffInHours(anomaly.getStartTime(), anomaly.getEndTime()), getDateString(anomaly.getStartTime(), dateTimeZone), getDateString(anomaly.getEndTime(), dateTimeZone), // duration
            getTimezoneString(dateTimeZone)), feedbackVal, anomaly.getFunction().getFunctionName(), // lift
            String.format("%+.2f%%", anomaly.getWeight() * 100), getLiftDirection(anomaly.getWeight()), anomaly.getMetric());
            if (anomaly.isNotified()) {
                alertedAnomalies++;
            }
            // include notified alerts only in the email
            if (includeSentAnomaliesOnly) {
                if (anomaly.isNotified()) {
                    anomalyReportDTOList.add(anomalyReportDTO);
                    anomalyIds.add(anomalyReportDTO.getAnomalyId());
                }
            } else {
                anomalyReportDTOList.add(anomalyReportDTO);
                anomalyIds.add(anomalyReportDTO.getAnomalyId());
            }
        }
        HtmlEmail email = new HtmlEmail();
        DateTimeZone timeZone = DateTimeZone.forTimeZone(AlertTaskRunnerV2.DEFAULT_TIME_ZONE);
        DataReportHelper.DateFormatMethod dateFormatMethod = new DataReportHelper.DateFormatMethod(timeZone);
        Map<String, Object> templateData = new HashMap<>();
        templateData.put("timeZone", timeZone);
        templateData.put("dateFormat", dateFormatMethod);
        templateData.put("startTime", startTime);
        templateData.put("endTime", endTime);
        templateData.put("anomalyCount", anomalies.size());
        templateData.put("metricsCount", metrics.size());
        templateData.put("notifiedCount", alertedAnomalies);
        templateData.put("feedbackCount", feedbackCollected);
        templateData.put("trueAlertCount", trueAlert);
        templateData.put("falseAlertCount", falseAlert);
        templateData.put("nonActionableCount", nonActionable);
        templateData.put("anomalyDetails", anomalyReportDTOList);
        templateData.put("alertConfigName", alertConfigName);
        templateData.put("includeSummary", includeSummary);
        templateData.put("reportGenerationTimeMillis", System.currentTimeMillis());
        templateData.put("dashboardHost", configuration.getDashboardHost());
        templateData.put("anomalyIds", Joiner.on(",").join(anomalyIds));
        boolean isSingleAnomalyEmail = false;
        String imgPath = null;
        if (anomalyReportDTOList.size() == 1) {
            isSingleAnomalyEmail = true;
            AnomalyReportDTO singleAnomaly = anomalyReportDTOList.get(0);
            subject = subject + " - " + singleAnomaly.getMetric();
            imgPath = EmailScreenshotHelper.takeGraphScreenShot(singleAnomaly.getAnomalyId(), configuration);
            String cid = "";
            try {
                cid = email.embed(new File(imgPath));
            } catch (Exception e) {
                LOG.error("Exception while embedding screenshot for anomaly {}", singleAnomaly.getAnomalyId(), e);
            }
            templateData.put("cid", cid);
        }
        buildEmailTemplateAndSendAlert(templateData, configuration.getSmtpConfiguration(), subject, emailRecipients, fromEmail, isSingleAnomalyEmail, email);
        if (StringUtils.isNotBlank(imgPath)) {
            try {
                Files.deleteIfExists(new File(imgPath).toPath());
            } catch (IOException e) {
                LOG.error("Exception in deleting screenshot {}", imgPath, e);
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HtmlEmail(org.apache.commons.mail.HtmlEmail) IOException(java.io.IOException) DateTimeZone(org.joda.time.DateTimeZone) IOException(java.io.IOException) MergedAnomalyResultDTO(com.linkedin.thirdeye.datalayer.dto.MergedAnomalyResultDTO) File(java.io.File) HashSet(java.util.HashSet)

Example 3 with HtmlEmail

use of org.apache.commons.mail.HtmlEmail in project c4sg-services by Code4SocialGood.

the class AsyncEmailServiceImpl method send.

/**
     * Sends an email message asynchronously.
     *
     * @param from       email address from which the message will be sent.
     * @param recipient  array of strings containing the recipients of the message.
     * @param subject    subject header field.
     * @param text       content of the message.
     */
@Async
public void send(String from, String recipient, String subject, String text) {
    try {
        Properties properties = new Properties();
        properties.load(getClass().getResourceAsStream("/mail.properties"));
        String host = properties.getProperty("mail.smtp.host");
        String port = properties.getProperty("mail.smtp.port");
        String ssl = properties.getProperty("mail.smtp.ssl.enable");
        String username = properties.getProperty("mail.smtp.username");
        String password = properties.getProperty("mail.smtp.password");
        HtmlEmail email = new HtmlEmail();
        email.setHostName(host);
        email.setSmtpPort(Integer.parseInt(port));
        email.setAuthentication(username, password);
        email.setSSLOnConnect(Boolean.parseBoolean(ssl));
        Objects.requireNonNull(from, "Sender's email is incorrect");
        Objects.requireNonNull(recipient, "Recipient's email is incorrect");
        email.setFrom(from);
        email.addTo(recipient);
        email.setSubject(subject);
        email.setHtmlMsg(text);
        email.send();
        System.out.println("Email sent to " + recipient + " successfully");
    } catch (EmailException e) {
        e.printStackTrace();
        System.out.println("Fail: Could not send email to: " + recipient + " !!! ");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : HtmlEmail(org.apache.commons.mail.HtmlEmail) EmailException(org.apache.commons.mail.EmailException) IOException(java.io.IOException) Properties(java.util.Properties) Async(org.springframework.scheduling.annotation.Async)

Example 4 with HtmlEmail

use of org.apache.commons.mail.HtmlEmail in project Gargoyle by callakrsos.

the class MimeConverter method simple.

@Test
public void simple() throws Exception {
    new ProxyInitializable().initialize();
    HtmlEmail email = new HtmlEmail();
    email.setHostName("mail.myserver.com");
    email.addTo("jdoe@somewhere.org", "John Doe");
    // email.setFrom("me@apache.org", "Me");
    email.setSubject("Test email with inline image");
    // embed the image and get the content id
    // URL url = new URL("https://i.stack.imgur.com/r7Nij.jpg?s=32&g=1");
    String cid = email.embed(new File("123.jpg"));
    // 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");
    MimeMessage mimeMessage = email.getMimeMessage();
    System.out.println(mimeMessage);
    System.out.println(email.sendMimeMessage());
    // send the email
    email.send();
}
Also used : ProxyInitializable(com.kyj.fx.voeditor.visual.main.initalize.ProxyInitializable) MimeMessage(javax.mail.internet.MimeMessage) HtmlEmail(org.apache.commons.mail.HtmlEmail) File(java.io.File) Test(org.junit.Test)

Example 5 with HtmlEmail

use of org.apache.commons.mail.HtmlEmail in project weicoder by wdcode.

the class EmailApache method sendHtmlEmail.

/**
 * 发送HTML格式带附件的邮件
 * @param to 发送地址
 * @param subject 邮件标题
 * @param msg 邮件内容
 * @param attach 附件
 */
protected final void sendHtmlEmail(String[] to, String subject, String msg, String attach) {
    // 实例化邮件操作类
    HtmlEmail email = new HtmlEmail();
    // 添加附件
    setAttachment(email, attach);
    // 发送Email
    sendEmail(email, to, subject, msg);
}
Also used : HtmlEmail(org.apache.commons.mail.HtmlEmail)

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