org.apache.commons.mail.HtmlEmail Java Examples

The following examples show how to use org.apache.commons.mail.HtmlEmail. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MailSenderDefaultImpl.java    From minsx-framework with Apache License 2.0 7 votes vote down vote up
public void finishInitial() {
    try {
        Integer sslPort = 465;
        simpleEmail = new SimpleEmail();
        simpleEmail.setHostName(this.host);
        simpleEmail.setSmtpPort(this.port);
        simpleEmail.setAuthentication(this.username, this.password);
        simpleEmail.setFrom(this.from);
        simpleEmail.setCharset("UTF-8");
        if (sslPort.equals(this.port)) {
            simpleEmail.setSSLOnConnect(true);
        }
        htmlEmail = new HtmlEmail();
        htmlEmail.setHostName(this.host);
        htmlEmail.setSmtpPort(this.port);
        htmlEmail.setAuthentication(this.username, this.password);
        htmlEmail.setFrom(this.from);
        htmlEmail.setCharset("UTF-8");
        if (sslPort.equals(this.port)) {
            htmlEmail.setSSLOnConnect(true);
        }
    } catch (EmailException e) {
        throw new MailSendException(String.format("Incorrect setting field of [from],cause: %s", e.getMessage()), e);
    }
}
 
Example #2
Source File: GeneralMailSender.java    From shepher with Apache License 2.0 6 votes vote down vote up
protected void send(String mailAddress, String title, String content) {
    if (StringUtils.isBlank(mailAddress)) {
        return;
    }

    try {
        Email email = new HtmlEmail();
        email.setHostName(hostname);
        email.setAuthenticator(new DefaultAuthenticator(username, password));
        email.setSmtpPort(port);
        email.setFrom(from, fromname);
        email.setSubject(title);
        email.setMsg(content);
        email.addTo(mailAddress.split(mailAddressEndSeparator));
        email.send();
    } catch (Exception e) {
        logger.error("Send Mail Error", e);
    }
}
 
Example #3
Source File: EmailMessageSender.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private HtmlEmail getHtmlEmail( String hostName, int port, String username, String password, boolean tls,
    String sender ) throws EmailException
{
    HtmlEmail email = new HtmlEmail();
    email.setHostName( hostName );
    email.setFrom( sender, getEmailName() );
    email.setSmtpPort( port );
    email.setStartTLSEnabled( tls );

    if ( username != null && password != null )
    {
        email.setAuthenticator( new DefaultAuthenticator( username, password ) );
    }

    return email;
}
 
Example #4
Source File: EmailService.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sends an email to the user with the temporary verification code.
 *
 * @param name the name of the player
 * @param mailAddress the player's email
 * @param code the verification code
 * @return true if email could be sent, false otherwise
 */
public boolean sendVerificationMail(String name, String mailAddress, String code) {
    if (!hasAllInformation()) {
        logger.warning("Cannot send verification email: not all email settings are complete");
        return false;
    }

    HtmlEmail email;
    try {
        email = sendMailSsl.initializeMail(mailAddress);
    } catch (EmailException e) {
        logger.logException("Failed to create verification email with the given settings:", e);
        return false;
    }

    String mailText = replaceTagsForVerificationEmail(settings.getVerificationEmailMessage(), name, code,
        settings.getProperty(SecuritySettings.VERIFICATION_CODE_EXPIRATION_MINUTES));
    return sendMailSsl.sendEmail(mailText, email);
}
 
Example #5
Source File: SendMailUtil.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 发送普通邮件
 * @param toMailAddr 收信人地址
 * @param subject email主题
 * @param message 发送email信息  
 */
public static void sendCommonMail(String toMailAddr, String subject, String message) {
	  HtmlEmail hemail = new HtmlEmail();
	try {
		hemail.setHostName(getHost(from));
		hemail.setSmtpPort(getSmtpPort(from));
		hemail.setCharset(charSet);
		hemail.addTo(toMailAddr);
		hemail.setFrom(from, fromName);
		hemail.setAuthentication(username, password);
		hemail.setSubject(subject);
		hemail.setMsg(message);
		hemail.send();
		org.jeecgframework.core.util.LogUtil.info("email send true!");
	} catch (Exception e) {
	      e.printStackTrace();
	      org.jeecgframework.core.util.LogUtil.info("email send error!");
	    }
	
}
 
Example #6
Source File: MailSender.java    From translationstudio8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 构造方法.
 * @param host
 *            邮件服务器,如:"mail.heartsome.net"
 * @param protocol
 *            邮件协议
 * @param port
 *            端口号
 * @param userName
 *            邮箱用户名
 * @param password
 *            邮箱密码
 * @param ssl
 *            是否应用 SSL 安全协议
 */
public MailSender(String host, String protocol, int port, String userName, String password, boolean ssl) {
	props = new Properties();
	if (port != -1) {
		this.port = port;
	}
	this.userName = userName;
	this.password = password;
	props.setProperty("mail." + protocol + ".auth", "true");
	props.setProperty("mail.transport.protocol", protocol);
	props.setProperty("mail.host", host);
	props.setProperty("mail." + protocol + ".port", "" + this.port);
	createSession();
	email = new HtmlEmail();
	email.setCharset("utf-8");
	email.setMailSession(session);
	if (ssl) {
		email.setSSL(true);
	}
}
 
Example #7
Source File: ReportMailer.java    From AisAbnormal with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Send email with subject and message body.
 * @param subject the email subject.
 * @param body the email body.
 */
public void send(String subject, String body) {
    try {
        HtmlEmail email = new HtmlEmail();
        email.setHostName(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_HOST, "localhost"));
        email.setSmtpPort(configuration.getInt(CONFKEY_REPORTS_MAILER_SMTP_PORT, 465));
        email.setAuthenticator(new DefaultAuthenticator(
            configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_USER, "anonymous"),
            configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_PASS, "guest")
        ));
        email.setStartTLSEnabled(false);
        email.setSSLOnConnect(configuration.getBoolean(CONFKEY_REPORTS_MAILER_SMTP_SSL, true));
        email.setFrom(configuration.getString(CONFKEY_REPORTS_MAILER_SMTP_FROM, ""));
        email.setSubject(subject);
        email.setHtmlMsg(body);
        String[] receivers = configuration.getStringArray(CONFKEY_REPORTS_MAILER_SMTP_TO);
        for (String receiver : receivers) {
            email.addTo(receiver);
        }
        email.send();
        LOG.info("Report sent with email to " + email.getToAddresses().toString() + " (\"" + subject + "\")");
    } catch (EmailException e) {
        LOG.error(e.getMessage(), e);
    }
}
 
Example #8
Source File: SendMailSslTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldCreateEmailObject() throws EmailException {
    // given
    given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(465);
    String smtpHost = "mail.example.com";
    given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost);
    String senderAccount = "[email protected]";
    given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderAccount);
    String senderName = "Server administration";
    given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn(senderName);
    given(settings.getProperty(PluginSettings.LOG_LEVEL)).willReturn(LogLevel.DEBUG);

    // when
    HtmlEmail email = sendMailSsl.initializeMail("[email protected]");

    // then
    assertThat(email, not(nullValue()));
    assertThat(email.getToAddresses(), hasSize(1));
    assertThat(email.getToAddresses().get(0).getAddress(), equalTo("[email protected]"));
    assertThat(email.getFromAddress().getAddress(), equalTo(senderAccount));
    assertThat(email.getFromAddress().getPersonal(), equalTo(senderName));
    assertThat(email.getHostName(), equalTo(smtpHost));
    assertThat(email.getSmtpPort(), equalTo("465"));
}
 
Example #9
Source File: SendMailUtil.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
/**
 * 发送普通邮件
 * 
 * @param toMailAddr
 *            收信人地址
 * @param subject
 *            email主题
 * @param message
 *            发送email信息
 */
public static void sendCommonMail(String toMailAddr, String subject,
		String message) {
	HtmlEmail hemail = new HtmlEmail();
	try {
		hemail.setHostName(getHost(from));
		hemail.setSmtpPort(getSmtpPort(from));
		hemail.setCharset(charSet);
		hemail.addTo(toMailAddr);
		hemail.setFrom(from, fromName);
		hemail.setAuthentication(username, password);
		hemail.setSubject(subject);
		hemail.setMsg(message);
		hemail.send();
		System.out.println("email send true!");
	} catch (Exception e) {
		e.printStackTrace();
		System.out.println("email send error!");
	}

}
 
Example #10
Source File: SendMailSslTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldCreateEmailObjectWithAddress() throws EmailException {
    // given
    given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(465);
    String smtpHost = "mail.example.com";
    given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost);
    String senderAccount = "exampleAccount";
    given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderAccount);
    String senderAddress = "[email protected]";
    given(settings.getProperty(EmailSettings.MAIL_ADDRESS)).willReturn(senderAddress);
    String senderName = "Server administration";
    given(settings.getProperty(EmailSettings.MAIL_SENDER_NAME)).willReturn(senderName);

    // when
    HtmlEmail email = sendMailSsl.initializeMail("[email protected]");

    // then
    assertThat(email, not(nullValue()));
    assertThat(email.getToAddresses(), hasSize(1));
    assertThat(email.getToAddresses().get(0).getAddress(), equalTo("[email protected]"));
    assertThat(email.getFromAddress().getAddress(), equalTo(senderAddress));
    assertThat(email.getFromAddress().getPersonal(), equalTo(senderName));
    assertThat(email.getHostName(), equalTo(smtpHost));
    assertThat(email.getSmtpPort(), equalTo("465"));
}
 
Example #11
Source File: MailUtil.java    From JARVIS with MIT License 6 votes vote down vote up
public void send(Mail mail) throws EmailException {  
    // ����email  
    HtmlEmail email = new HtmlEmail();  
    // ������SMTP���ͷ����������֣�163�����£�"smtp.163.com"  
    email.setHostName(mail.getHost());  
    // �ַ����뼯������  
    email.setCharset(Mail.ENCODEING);  
    // �ռ��˵�����  
    email.addTo(mail.getReceiver());  
    // �����˵�����  
    email.setFrom(mail.getSender(), mail.getName());  
    // �����Ҫ��֤��Ϣ�Ļ���������֤���û���-���롣�ֱ�Ϊ���������ʼ��������ϵ�ע�����ƺ�����  
    email.setAuthentication(mail.getUsername(), mail.getPassword());  
    // Ҫ���͵��ʼ�����  
    email.setSubject(mail.getSubject());  
    // Ҫ���͵���Ϣ������ʹ����HtmlEmail���������ʼ�������ʹ��HTML��ǩ  
    email.setMsg(mail.getMessage());  
    //��Ӹ���
    if(mail.getAttachment()!=null)
    	email.attach(mail.getAttachment());
    // ����  
    email.send();  
    System.out.println(mail.getSender() + " �����ʼ��� " + mail.getReceiver());  
}
 
Example #12
Source File: SendMailSslTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldCreateEmailObjectWithOAuth2() throws EmailException {
    // given
    given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(587);
    given(settings.getProperty(EmailSettings.OAUTH2_TOKEN)).willReturn("oAuth2 token");
    String smtpHost = "mail.example.com";
    given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost);
    String senderMail = "[email protected]";
    given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderMail);

    // when
    HtmlEmail email = sendMailSsl.initializeMail("[email protected]");

    // then
    assertThat(email, not(nullValue()));
    assertThat(email.getToAddresses(), hasSize(1));
    assertThat(email.getToAddresses().get(0).getAddress(), equalTo("[email protected]"));
    assertThat(email.getFromAddress().getAddress(), equalTo(senderMail));
    assertThat(email.getHostName(), equalTo(smtpHost));
    assertThat(email.getSmtpPort(), equalTo("587"));

    Properties mailProperties = email.getMailSession().getProperties();
    assertThat(mailProperties.getProperty("mail.smtp.auth.mechanisms"), equalTo("XOAUTH2"));
    assertThat(mailProperties.getProperty("mail.smtp.auth.plain.disable"), equalTo("true"));
    assertThat(mailProperties.getProperty(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP), equalTo("oAuth2 token"));
}
 
Example #13
Source File: EmailHandler.java    From robozonky with Apache License 2.0 6 votes vote down vote up
private HtmlEmail createNewEmail(final SessionInfo session) throws EmailException {
    final HtmlEmail email = new HtmlEmail();
    email.setCharset(Defaults.CHARSET.displayName()); // otherwise the e-mail contents are mangled
    email.setHostName(getSmtpHostname());
    email.setSmtpPort(getSmtpPort());
    email.setStartTLSRequired(isStartTlsRequired());
    email.setSSLOnConnect(isSslOnConnectRequired());
    if (isAuthenticationRequired()) {
        final String username = getSmtpUsername();
        LOGGER.debug("Will contact SMTP server as '{}'.", username);
        email.setAuthentication(getSmtpUsername(), getSmtpPassword());
    } else {
        LOGGER.debug("Will contact SMTP server anonymously.");
    }
    email.setFrom(getSender(), "RoboZonky '" + session.getName() + "'");
    email.addTo(getRecipient());
    return email;
}
 
Example #14
Source File: EmailServiceTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldSendPasswordMail() throws EmailException {
    // given
    given(settings.getPasswordEmailMessage())
        .willReturn("Hi <playername />, your new password for <servername /> is <generatedpass />");
    given(settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)).willReturn(false);
    HtmlEmail email = mock(HtmlEmail.class);
    given(sendMailSsl.initializeMail(anyString())).willReturn(email);
    given(sendMailSsl.sendEmail(anyString(), eq(email))).willReturn(true);

    // when
    boolean result = emailService.sendPasswordMail("Player", "[email protected]", "new_password");

    // then
    assertThat(result, equalTo(true));
    verify(sendMailSsl).initializeMail("[email protected]");
    ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
    verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email));
    assertThat(messageCaptor.getValue(),
        equalTo("Hi Player, your new password for serverName is new_password"));
}
 
Example #15
Source File: DetectionEmailAlerterTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendEmailSuccessful() throws Exception {
  Map<DetectionAlertFilterNotification, Set<MergedAnomalyResultDTO>> result = new HashMap<>();
  DetectionAlertConfigDTO subsConfig = SubscriptionUtils.makeChildSubscriptionConfig(
      this.alertConfigDTO,
      ConfigUtils.getMap(this.alertConfigDTO.getAlertSchemes()),
      new HashMap<>());
  result.put(
      new DetectionAlertFilterNotification(subsConfig),
      new HashSet<>(this.anomalyDAO.findAll()));
  DetectionAlertFilterResult notificationResults = new DetectionAlertFilterResult(result);

  final HtmlEmail htmlEmail = mock(HtmlEmail.class);
  when(htmlEmail.send()).thenReturn("sent");

  DetectionEmailAlerter emailAlerter = new DetectionEmailAlerter(this.alertConfigDTO, this.thirdEyeConfig, notificationResults) {
    @Override
    protected HtmlEmail getHtmlContent(EmailEntity emailEntity) {
      return htmlEmail;
    }
  };
  // Executes successfully without errors
  emailAlerter.run();
}
 
Example #16
Source File: EmailServiceTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldHandleMailSendingFailure() throws EmailException {
    // given
    given(settings.getPasswordEmailMessage()).willReturn("Hi <playername />, your new pass is <generatedpass />");
    given(settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)).willReturn(false);
    HtmlEmail email = mock(HtmlEmail.class);
    given(sendMailSsl.initializeMail(anyString())).willReturn(email);
    given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(false);

    // when
    boolean result = emailService.sendPasswordMail("bobby", "[email protected]", "myPassw0rd");

    // then
    assertThat(result, equalTo(false));
    verify(sendMailSsl).initializeMail("[email protected]");
    ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
    verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email));
    assertThat(messageCaptor.getValue(), equalTo("Hi bobby, your new pass is myPassw0rd"));
}
 
Example #17
Source File: EmailServiceTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldSendRecoveryCode() throws EmailException {
    // given
    given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(7);
    given(settings.getRecoveryCodeEmailMessage())
        .willReturn("Hi <playername />, your code on <servername /> is <recoverycode /> (valid <hoursvalid /> hours)");
    HtmlEmail email = mock(HtmlEmail.class);
    given(sendMailSsl.initializeMail(anyString())).willReturn(email);
    given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(true);

    // when
    boolean result = emailService.sendRecoveryCode("Timmy", "[email protected]", "12C56A");

    // then
    assertThat(result, equalTo(true));
    verify(sendMailSsl).initializeMail("[email protected]");
    ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
    verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email));
    assertThat(messageCaptor.getValue(), equalTo("Hi Timmy, your code on serverName is 12C56A (valid 7 hours)"));
}
 
Example #18
Source File: MonitorTaskRunner.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private void sendDisableAlertNotificationEmail(DetectionConfigDTO config) throws EmailException {
  HtmlEmail email = new HtmlEmail();
  String subject = String.format("ThirdEye alert disabled: %s", config.getName());
  String textBody = String.format(
      "Your alert has failed for %d days and was disabled. Please fix your alert and enable it again. \n" + "Here is the link for your alert: https://thirdeye.corp.linkedin.com/app/#/manage/explore/%d",
      MAX_FAILED_DISABLE_DAYS, config.getId());
  Set<String> recipients = EmailUtils.getValidEmailAddresses(thirdeyeConfig.getFailureToAddress());
  if (config.getCreatedBy() != null && !config.getCreatedBy().equals("no-auth-user")) {
    recipients.add(config.getCreatedBy());
  }
  if (config.getUpdatedBy() != null && !config.getUpdatedBy().equals("no-auth-user")) {
    recipients.add(config.getUpdatedBy());
  }
  EmailHelper.sendEmailWithTextBody(email,
      SmtpConfiguration.createFromProperties(thirdeyeConfig.getAlerterConfiguration().get(SMTP_CONFIG_KEY)), subject,
      textBody, thirdeyeConfig.getFailureFromAddress(), new DetectionAlertFilterRecipients(recipients));
}
 
Example #19
Source File: EmailServiceTest.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void shouldHandleFailureToSendRecoveryCode() throws EmailException {
    // given
    given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(7);
    given(settings.getRecoveryCodeEmailMessage()).willReturn("Hi <playername />, your code is <recoverycode />");
    EmailService sendMailSpy = spy(emailService);
    HtmlEmail email = mock(HtmlEmail.class);
    given(sendMailSsl.initializeMail(anyString())).willReturn(email);
    given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(false);

    // when
    boolean result = sendMailSpy.sendRecoveryCode("John", "[email protected]", "1DEF77");

    // then
    assertThat(result, equalTo(false));
    verify(sendMailSsl).initializeMail("[email protected]");
    ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
    verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email));
    assertThat(messageCaptor.getValue(), equalTo("Hi John, your code is 1DEF77"));
}
 
Example #20
Source File: MailSender.java    From tmxeditor8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 构造方法.
 * @param host
 *            邮件服务器,如:"mail.heartsome.net"
 * @param protocol
 *            邮件协议
 * @param port
 *            端口号
 * @param userName
 *            邮箱用户名
 * @param password
 *            邮箱密码
 * @param ssl
 *            是否应用 SSL 安全协议
 */
public MailSender(String host, String protocol, int port, String userName, String password, boolean ssl) {
	props = new Properties();
	if (port != -1) {
		this.port = port;
	}
	this.userName = userName;
	this.password = password;
	props.setProperty("mail." + protocol + ".auth", "true");
	props.setProperty("mail.transport.protocol", protocol);
	props.setProperty("mail.host", host);
	props.setProperty("mail." + protocol + ".port", "" + this.port);
	createSession();
	email = new HtmlEmail();
	email.setCharset("utf-8");
	email.setMailSession(session);
	if (ssl) {
		email.setSSL(true);
	}
}
 
Example #21
Source File: Mailer.java    From judgels with GNU General Public License v2.0 6 votes vote down vote up
public void send(String recipient, String subject, String body) {
    new Thread(() -> {
        try {
            HtmlEmail email = new HtmlEmail();
            email.setHostName(config.getHost());
            email.setSmtpPort(config.getPort());
            email.setAuthenticator(new DefaultAuthenticator(config.getUsername(), config.getPassword()));
            email.setSSLOnConnect(config.getUseSsl());
            email.setFrom(config.getSender());
            email.setSubject(subject);
            email.setHtmlMsg(body);
            email.addTo(recipient);
            email.send();
        } catch (EmailException e) {
            throw new RuntimeException(e);
        }
    }).start();
}
 
Example #22
Source File: SendMailUtil.java    From jeewx-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 发送普通邮件
 * @param toMailAddr 收信人地址
 * @param subject email主题
 * @param message 发送email信息  
 */
public static boolean sendCommonMail(String toMailAddr, String subject, String message) {
	  HtmlEmail hemail = new HtmlEmail();
	try {
		SystemProperties systemProperties = ApplicationContextUtil.getBean(SystemProperties.class);
		hemail.setHostName(systemProperties.getSmtpHost());
		hemail.setSmtpPort(getSmtpPort(systemProperties.getSender()));
		hemail.setCharset(charSet);
		hemail.addTo(toMailAddr);
		hemail.setFrom(systemProperties.getSender(), fromName);
		hemail.setAuthentication(systemProperties.getUser(), systemProperties.getPwd());
		hemail.setSubject(subject);
		hemail.setMsg(message);
		hemail.send();
		log.info("send email to "+toMailAddr+" OK!");
		return true;
	} catch (Exception e) {
	      e.printStackTrace();
	      log.info("send email to "+toMailAddr+" error!"+ e.toString());
	      return false;
	}
}
 
Example #23
Source File: EmailHelper.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public static void sendNotificationForDataIncomplete(
    Multimap<String, DataCompletenessConfigDTO> incompleteEntriesToNotify, ThirdEyeAnomalyConfiguration thirdeyeConfig) {
  HtmlEmail email = new HtmlEmail();
  String subject = String.format("Data Completeness Checker Report");
  StringBuilder textBody = new StringBuilder();
  for (String dataset : incompleteEntriesToNotify.keySet()) {
    List<DataCompletenessConfigDTO> entries = Lists.newArrayList(incompleteEntriesToNotify.get(dataset));
    textBody.append(String.format("\nDataset: %s\n", dataset));
    for (DataCompletenessConfigDTO entry : entries) {
      textBody.append(String.format("%s ", entry.getDateToCheckInSDF()));
    }
    textBody.append("\n*******************************************************\n");
  }
  LOG.info("Data Completeness Checker Report : Sending email to {} with subject {} and text {}",
      thirdeyeConfig.getFailureToAddress(), subject, textBody.toString());

  try {
    EmailHelper.sendEmailWithTextBody(email,
        SmtpConfiguration.createFromProperties(thirdeyeConfig.getAlerterConfiguration().get(SMTP_CONFIG_KEY)),
        subject, textBody.toString(), thirdeyeConfig.getFailureFromAddress(),
        new DetectionAlertFilterRecipients(EmailUtils.getValidEmailAddresses(thirdeyeConfig.getFailureToAddress())));
  } catch (EmailException e) {
    LOG.error("Exception in sending email notification for incomplete datasets", e);
  }

}
 
Example #24
Source File: SendMailUtil.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 发送普通邮件
 * @param toMailAddr 收信人地址
 * @param subject email主题
 * @param message 发送email信息  
 */
public static void sendCommonMail(String toMailAddr, String subject, String message) {
	  HtmlEmail hemail = new HtmlEmail();
	try {
		hemail.setHostName(getHost(from));
		hemail.setSmtpPort(getSmtpPort(from));
		hemail.setCharset(charSet);
		hemail.addTo(toMailAddr);
		hemail.setFrom(from, fromName);
		hemail.setAuthentication(username, password);
		hemail.setSubject(subject);
		hemail.setMsg(message);
		hemail.send();
		org.jeecgframework.core.util.LogUtil.info("email send true!");
	} catch (Exception e) {
	      e.printStackTrace();
	      org.jeecgframework.core.util.LogUtil.info("email send error!");
	    }
	
}
 
Example #25
Source File: MimeMessageParserTest.java    From commons-email with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseCreatedHtmlEmailWithTextContent() throws Exception
{
    final Session session = Session.getDefaultInstance(new Properties());

    final HtmlEmail email = new HtmlEmail();

    email.setMailSession(session);

    email.setFrom("[email protected]");
    email.setSubject("Test Subject");
    email.addTo("[email protected]");
    email.setTextMsg("My test message");

    email.buildMimeMessage();
    final MimeMessage msg = email.getMimeMessage();

    final MimeMessageParser mimeMessageParser = new MimeMessageParser(msg);
    mimeMessageParser.parse();

    assertEquals("Test Subject", mimeMessageParser.getSubject());
    assertNotNull(mimeMessageParser.getMimeMessage());
    assertTrue(mimeMessageParser.isMultipart());
    assertFalse(mimeMessageParser.hasHtmlContent());
    assertTrue(mimeMessageParser.hasPlainContent());
    assertNotNull(mimeMessageParser.getPlainContent());
    assertNull(mimeMessageParser.getHtmlContent());
    assertTrue(mimeMessageParser.getTo().size() == 1);
    assertTrue(mimeMessageParser.getCc().size() == 0);
    assertTrue(mimeMessageParser.getBcc().size() == 0);
    assertEquals("[email protected]", mimeMessageParser.getFrom());
    assertEquals("[email protected]", mimeMessageParser.getReplyTo());
    assertFalse(mimeMessageParser.hasAttachments());
}
 
Example #26
Source File: MimeMessageParserTest.java    From commons-email with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseCreatedHtmlEmailWithNoContent() throws Exception
{
    final Session session = Session.getDefaultInstance(new Properties());

    final HtmlEmail email = new HtmlEmail();

    email.setMailSession(session);

    email.setFrom("[email protected]");
    email.setSubject("Test Subject");
    email.addTo("[email protected]");

    email.buildMimeMessage();
    final MimeMessage msg = email.getMimeMessage();

    final MimeMessageParser mimeMessageParser = new MimeMessageParser(msg);
    mimeMessageParser.parse();

    assertEquals("Test Subject", mimeMessageParser.getSubject());
    assertNotNull(mimeMessageParser.getMimeMessage());
    assertTrue(mimeMessageParser.isMultipart());
    assertFalse(mimeMessageParser.hasHtmlContent());
    assertFalse(mimeMessageParser.hasPlainContent());
    assertNull(mimeMessageParser.getPlainContent());
    assertNull(mimeMessageParser.getHtmlContent());
    assertTrue(mimeMessageParser.getTo().size() == 1);
    assertTrue(mimeMessageParser.getCc().size() == 0);
    assertTrue(mimeMessageParser.getBcc().size() == 0);
    assertEquals("[email protected]", mimeMessageParser.getFrom());
    assertEquals("[email protected]", mimeMessageParser.getReplyTo());
    assertFalse(mimeMessageParser.hasAttachments());
}
 
Example #27
Source File: EmailHelper.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/** Sends email according to the provided config. */
private static void sendEmail(SmtpConfiguration config, HtmlEmail email, String subject,
    String fromAddress, DetectionAlertFilterRecipients recipients) throws EmailException {
  if (config != null) {
    email.setSubject(subject);
    LOG.info("Sending email to {}", recipients.toString());
    email.setHostName(config.getSmtpHost());
    email.setSmtpPort(config.getSmtpPort());
    if (config.getSmtpUser() != null && config.getSmtpPassword() != null) {
      email.setAuthenticator(
          new DefaultAuthenticator(config.getSmtpUser(), config.getSmtpPassword()));
      email.setSSLOnConnect(true);
    }
    email.setFrom(fromAddress);
    email.setTo(AlertUtils.toAddress(recipients.getTo()));
    if (CollectionUtils.isNotEmpty(recipients.getCc())) {
      email.setCc(AlertUtils.toAddress(recipients.getCc()));
    }
    if (CollectionUtils.isNotEmpty(recipients.getBcc())) {
      email.setBcc(AlertUtils.toAddress(recipients.getBcc()));
    }
    email.send();
    LOG.info("Email sent with subject [{}] to address [{}]!", subject, recipients.toString());
  } else {
    LOG.error("No email config provided for email with subject [{}]!", subject);
  }
}
 
Example #28
Source File: MimeMessageParserTest.java    From commons-email with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseCreatedHtmlEmailWithMixedContent() throws Exception
{
    final Session session = Session.getDefaultInstance(new Properties());

    final HtmlEmail email = new HtmlEmail();

    email.setMailSession(session);

    email.setFrom("[email protected]");
    email.setSubject("Test Subject");
    email.addTo("[email protected]");
    email.setTextMsg("My test message");
    email.setHtmlMsg("<p>My HTML message</p>");

    email.buildMimeMessage();
    final MimeMessage msg = email.getMimeMessage();

    final MimeMessageParser mimeMessageParser = new MimeMessageParser(msg);
    mimeMessageParser.parse();

    assertEquals("Test Subject", mimeMessageParser.getSubject());
    assertNotNull(mimeMessageParser.getMimeMessage());
    assertTrue(mimeMessageParser.isMultipart());
    assertTrue(mimeMessageParser.hasHtmlContent());
    assertTrue(mimeMessageParser.hasPlainContent());
    assertNotNull(mimeMessageParser.getPlainContent());
    assertNotNull(mimeMessageParser.getHtmlContent());
    assertTrue(mimeMessageParser.getTo().size() == 1);
    assertTrue(mimeMessageParser.getCc().size() == 0);
    assertTrue(mimeMessageParser.getBcc().size() == 0);
    assertEquals("[email protected]", mimeMessageParser.getFrom());
    assertEquals("[email protected]", mimeMessageParser.getReplyTo());
    assertFalse(mimeMessageParser.hasAttachments());
}
 
Example #29
Source File: ContentFormatterUtils.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
public static String getEmailHtml(EmailEntity emailEntity) throws Exception {
  HtmlEmail email = emailEntity.getContent();
  Field field = email.getClass().getDeclaredField("html");
  field.setAccessible(true);

  return field.get(email).toString();
}
 
Example #30
Source File: DetectionEmailAlerter.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private HtmlEmail prepareEmailContent(DetectionAlertConfigDTO subsConfig, Properties emailClientConfigs,
    List<AnomalyResult> anomalies, DetectionAlertFilterRecipients recipients) throws Exception {
  configureAdminRecipients(recipients);
  whitelistRecipients(recipients);
  blacklistRecipients(recipients);
  validateAlert(recipients, anomalies);

  BaseNotificationContent content = buildNotificationContent(emailClientConfigs);
  EmailEntity emailEntity = new EmailContentFormatter(emailClientConfigs, content, this.teConfig, subsConfig)
      .getEmailEntity(anomalies);
  if (Strings.isNullOrEmpty(this.subsConfig.getFrom())) {
    String fromAddress = MapUtils.getString(this.teConfig.getAlerterConfiguration().get(SMTP_CONFIG_KEY), PROP_FROM_ADDRESS);
    if (Strings.isNullOrEmpty(fromAddress)) {
      throw new IllegalArgumentException("Invalid sender's email");
    }
    this.subsConfig.setFrom(fromAddress);
  }

  HtmlEmail email = emailEntity.getContent();
  email.setSubject(emailEntity.getSubject());
  email.setFrom(this.subsConfig.getFrom());
  email.setTo(AlertUtils.toAddress(recipients.getTo()));
  if (!CollectionUtils.isEmpty(recipients.getCc())) {
    email.setCc(AlertUtils.toAddress(recipients.getCc()));
  }
  if (!CollectionUtils.isEmpty(recipients.getBcc())) {
    email.setBcc(AlertUtils.toAddress(recipients.getBcc()));
  }

  return getHtmlContent(emailEntity);
}