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 Project: minsx-framework   Author: MinsxCloud   File: MailSenderDefaultImpl.java    License: 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 Project: jeewx-boot   Author: zhangdaiscott   File: SendMailUtil.java    License: 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 #3
Source Project: judgels   Author: ia-toki   File: Mailer.java    License: 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 #4
Source Project: shepher   Author: XiaoMi   File: GeneralMailSender.java    License: 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 #5
Source Project: robozonky   Author: RoboZonky   File: EmailHandler.java    License: 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 #6
Source Project: JARVIS   Author: pokerfaceSad   File: MailUtil.java    License: 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 #7
Source Project: Shop-for-JavaWeb   Author: EleTeam   File: SendMailUtil.java    License: 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 #8
Source Project: dhis2-core   Author: dhis2   File: EmailMessageSender.java    License: 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 #9
Source Project: jeewx   Author: zhangdaiscott   File: SendMailUtil.java    License: 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 #10
Source Project: translationstudio8   Author: heartsome   File: MailSender.java    License: 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 #11
Source Project: tmxeditor8   Author: heartsome   File: MailSender.java    License: 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 #12
Source Project: incubator-pinot   Author: apache   File: EmailHelper.java    License: 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 #13
Source Project: incubator-pinot   Author: apache   File: MonitorTaskRunner.java    License: 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 #14
Source Project: incubator-pinot   Author: apache   File: DetectionEmailAlerterTest.java    License: 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 #15
Source Project: AisAbnormal   Author: dma-ais   File: ReportMailer.java    License: 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 #16
Source Project: AuthMeReloaded   Author: AuthMe   File: EmailService.java    License: 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 #17
Source Project: AuthMeReloaded   Author: AuthMe   File: SendMailSslTest.java    License: 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 #18
Source Project: AuthMeReloaded   Author: AuthMe   File: SendMailSslTest.java    License: 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 #19
Source Project: AuthMeReloaded   Author: AuthMe   File: SendMailSslTest.java    License: 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 #20
Source Project: AuthMeReloaded   Author: AuthMe   File: EmailServiceTest.java    License: 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 #21
Source Project: AuthMeReloaded   Author: AuthMe   File: EmailServiceTest.java    License: 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 #22
Source Project: AuthMeReloaded   Author: AuthMe   File: EmailServiceTest.java    License: 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 #23
Source Project: AuthMeReloaded   Author: AuthMe   File: EmailServiceTest.java    License: 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 #24
Source Project: jeecg   Author: zhangdaiscott   File: SendMailUtil.java    License: 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 Project: open-capacity-platform   Author: open-capacity-platform   File: MailUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @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(PropertiesUtil.getString("xxl.job.mail.host"));

		if ("true".equals(PropertiesUtil.getString("xxl.job.mail.ssl"))) {
			email.setSslSmtpPort(PropertiesUtil.getString("xxl.job.mail.port"));
			email.setSSLOnConnect(true);
		} else {
			email.setSmtpPort(Integer.valueOf(PropertiesUtil.getString("xxl.job.mail.port")));
		}

		email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getString("xxl.job.mail.username"), 
				PropertiesUtil.getString("xxl.job.mail.password")));
		email.setCharset(Charset.defaultCharset().name());

		email.setFrom(PropertiesUtil.getString("xxl.job.mail.username"), PropertiesUtil.getString("xxl.job.mail.sendNick"));
		email.addTo(toAddress);
		email.setSubject(mailSubject);
		email.setMsg(mailBody);

		//email.attach(attachment);	// add the attachment

		email.send();				// send the email
		return true;
	} catch (EmailException e) {
		logger.error(e.getMessage(), e);

	}
	return false;
}
 
Example #26
Source Project: frpMgr   Author: Zo3i   File: EmailUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 发送邮件
 * @param toAddress 接收地址
 * @param subject 标题
 * @param content 内容
 * @return
 */
public static boolean send(String fromAddress, String fromPassword, String fromHostName,
		String sslOnConnect, String sslSmtpPort, String toAddress, String subject, String content) {
	try {
		HtmlEmail htmlEmail = new HtmlEmail();
		// 发送地址
		htmlEmail.setFrom(fromAddress);
		// 密码校验
		htmlEmail.setAuthentication(fromAddress, fromPassword);
		// 发送服务器协议
		htmlEmail.setHostName(fromHostName);

		// SSL
		if ("true".equals(sslOnConnect)) {
			htmlEmail.setSSLOnConnect(true);
			htmlEmail.setSslSmtpPort(sslSmtpPort);
		}

		// 接收地址
		htmlEmail.addTo(toAddress);

		// 标题
		htmlEmail.setSubject(subject);
		// 内容
		htmlEmail.setMsg(content);

		// 其他信息
		htmlEmail.setCharset("utf-8");
		
		// 发送
		htmlEmail.send();
		return true;
	} catch (Exception ex) {
		logger.error(ex.getMessage(), ex);
	}
	return false;
}
 
Example #27
Source Project: zuihou-admin-boot   Author: zuihou   File: MailUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @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());

        if (XxlJobAdminConfig.getAdminConfig().isMailSSL()) {
            email.setSslSmtpPort(XxlJobAdminConfig.getAdminConfig().getMailPort());
            email.setSSLOnConnect(true);
        } else {
            email.setSmtpPort(Integer.valueOf(XxlJobAdminConfig.getAdminConfig().getMailPort()));
        }

        email.setAuthenticator(new DefaultAuthenticator(XxlJobAdminConfig.getAdminConfig().getMailUsername(), XxlJobAdminConfig.getAdminConfig().getMailPassword()));
        email.setCharset("UTF-8");

        email.setFrom(XxlJobAdminConfig.getAdminConfig().getMailUsername(), XxlJobAdminConfig.getAdminConfig().getMailSendNick());
        email.addTo(toAddress);
        email.setSubject(mailSubject);
        email.setMsg(mailBody);

        //email.attach(attachment);	// add the attachment

        email.send();                // send the email
        return true;
    } catch (EmailException e) {
        logger.error(e.getMessage(), e);

    }
    return false;
}
 
Example #28
Source Project: SpringMVC-Project   Author: MartinDai   File: EmailUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 发送HTML格式邮件
 */
public static void sendHtmlEmail(Authenticator authenticator, String hostName, Tuple2<String, String> fromInfo, List<Tuple2<String, String>> toList, List<Tuple2<String, String>> ccList, String subject, String htmlContent) throws EmailException {
    HtmlEmail htmlEmail = buildHtmlEmail(authenticator, hostName, fromInfo, toList, ccList, subject);
    htmlEmail.setHtmlMsg(htmlContent);

    htmlEmail.send();
}
 
Example #29
Source Project: zuihou-admin-cloud   Author: zuihou   File: MailUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @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());

        if (XxlJobAdminConfig.getAdminConfig().isMailSSL()) {
            email.setSslSmtpPort(XxlJobAdminConfig.getAdminConfig().getMailPort());
            email.setSSLOnConnect(true);
        } else {
            email.setSmtpPort(Integer.valueOf(XxlJobAdminConfig.getAdminConfig().getMailPort()));
        }

        email.setAuthenticator(new DefaultAuthenticator(XxlJobAdminConfig.getAdminConfig().getMailUsername(), XxlJobAdminConfig.getAdminConfig().getMailPassword()));
        email.setCharset("UTF-8");

        email.setFrom(XxlJobAdminConfig.getAdminConfig().getMailUsername(), XxlJobAdminConfig.getAdminConfig().getMailSendNick());
        email.addTo(toAddress);
        email.setSubject(mailSubject);
        email.setMsg(mailBody);

        //email.attach(attachment);	// add the attachment

        email.send();                // send the email
        return true;
    } catch (EmailException e) {
        logger.error(e.getMessage(), e);

    }
    return false;
}
 
Example #30
Source Project: activiti6-boot2   Author: dingziyang   File: MailActivityBehavior.java    License: Apache License 2.0 5 votes vote down vote up
protected HtmlEmail createHtmlEmail(String text, String html) {
  HtmlEmail email = new HtmlEmail();
  try {
    email.setHtmlMsg(html);
    if (text != null) { // for email clients that don't support html
      email.setTextMsg(text);
    }
    return email;
  } catch (EmailException e) {
    throw new ActivitiException("Could not create HTML email", e);
  }
}