Java Code Examples for org.apache.commons.mail.HtmlEmail#setTextMsg()

The following examples show how to use org.apache.commons.mail.HtmlEmail#setTextMsg() . 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: MailActivityBehavior.java    From activiti6-boot2 with 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);
  }
}
 
Example 2
Source File: MailActivityBehavior.java    From activiti6-boot2 with 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);
  }
}
 
Example 3
Source File: EmailHandler.java    From robozonky with Apache License 2.0 5 votes vote down vote up
@Override
public void send(final SessionInfo sessionInfo, final String subject,
        final String message, final String fallbackMessage) throws Exception {
    final HtmlEmail email = createNewEmail(sessionInfo);
    email.setSubject(subject);
    email.setHtmlMsg(message);
    email.setTextMsg(fallbackMessage);
    LOGGER.debug("Will send '{}' from {} to {} through {}:{} as {}.", email.getSubject(),
            email.getFromAddress(), email.getToAddresses(), email.getHostName(), email.getSmtpPort(),
            getSmtpUsername());
    email.send();
}
 
Example 4
Source File: MailActivityBehavior.java    From flowable-engine with 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 FlowableException("Could not create HTML email", e);
    }
}
 
Example 5
Source File: MailActivityBehavior.java    From flowable-engine with 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 FlowableException("Could not create HTML email", e);
    }
}
 
Example 6
Source File: MailActivityBehavior.java    From flowable-engine with 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);
    }
}
 
Example 7
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 8
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 9
Source File: MailActivityBehavior.java    From camunda-bpm-platform with 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 LOG.emailCreationException("HTML", e);
  }
}
 
Example 10
Source File: SendEmaiWithGmail.java    From spring-boot with Apache License 2.0 4 votes vote down vote up
/**
 * 发送 html 格式的邮件
 * 
 * @param userName
 * @param password
 * @param subject
 * @param from
 * @param to
 * @param cc
 * @param bcc
 * @throws EmailException
 * @throws java.net.MalformedURLException
 */
public void sendHTMLEmail(String userName, String password, String subject,
		String from, String to, String cc, String bcc)
		throws EmailException, MalformedURLException {

	// 创建SimpleEmail对象
	HtmlEmail email = new HtmlEmail();

	// 显示调试信息用于IED中输出
	email.setDebug(true);

	// 设置发送电子邮件的邮件服务器
	email.setHostName("smtp.gmail.com");

	// 邮件服务器是否使用ssl加密方式gmail就是,163就不是)
	email.setSSL(Boolean.TRUE);

	// 设置smtp端口号(需要查看邮件服务器的说明ssl加密之后端口号是不一样的)
	email.setSmtpPort(465);

	// 设置发送人的账号/密码
	email.setAuthentication(userName, password);

	// 显示的发信人地址,实际地址为gmail的地址
	email.setFrom(from);
	// 设置发件人的地址/称呼
	// email.setFrom("[email protected]", "发送人");

	// 收信人地址
	email.addTo(to);
	// 设置收件人的账号/称呼)
	// email.addTo("[email protected]", "收件人");

	// 多个抄送地址
	StrTokenizer stokenCC = new StrTokenizer(cc.trim(), ";");
	// 开始逐个抄送地址
	for (int i = 0; i < stokenCC.getTokenArray().length; i++) {
		email.addCc((String) stokenCC.getTokenArray()[i]);
	}

	// 多个密送送地址
	StrTokenizer stokenBCC = new StrTokenizer(bcc.trim(), ";");
	// 开始逐个抄送地址
	for (int i = 0; i < stokenBCC.getTokenArray().length; i++) {
		email.addBcc((String) stokenBCC.getTokenArray()[i]);
	}

	// Set the charset of the message.
	email.setCharset("UTF-8");

	email.setSentDate(new Date());

	// 设置标题,但是不能设置编码,commons 邮件的缺陷
	email.setSubject(subject);

	// === 以上同 simpleEmail

	// ===html mail 内容
	StringBuffer msg = new StringBuffer();
	msg.append("<html><body>");
	// 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");
	msg.append("<img src=\"cid:").append(cid).append("\">");

	// 本地图片
	File img = new File("d:/java.gif");
	msg.append("<img src=cid:").append(email.embed(img)).append(">");
	msg.append("</body></html>");

	// === html mail 内容

	// ==== // set the html message
	email.setHtmlMsg(msg.toString());
	// set the alternative message
	email.setTextMsg("Your email client does not support HTML messages");
	// send the email
	email.send();
	System.out.println("The HtmlEmail send sucessful!");

}
 
Example 11
Source File: RegistrationController.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value={"/register"})
public ModelAndView reg(@ModelAttribute("registration") Registration registration) {
	_logger.debug("Registration  /registration/register.");
	_logger.debug(""+registration);
	ModelAndView modelAndView= new ModelAndView("registration/registered");
	
	UserInfo userInfo =registrationService.queryUserInfoByEmail(registration.getWorkEmail());
	
	if(userInfo!=null){
		modelAndView.addObject("registered", 1);
		return modelAndView;
	}
	
	registration.setId(registration.generateId());
	registrationService.insert(registration);
	HtmlEmail email = new HtmlEmail();
	  
	  try {
		email.setHostName(applicationConfig.getEmailConfig().getSmtpHost());
		email.setSmtpPort(applicationConfig.getEmailConfig().getPort());
		email.setAuthenticator(new DefaultAuthenticator(applicationConfig.getEmailConfig().getUsername(), applicationConfig.getEmailConfig().getPassword()));
		
		email.addTo(registration.getWorkEmail(), registration.getLastName()+registration.getFirstName());
		email.setFrom(applicationConfig.getEmailConfig().getSender(), "ConnSec");
		email.setSubject("ConnSec Cloud Identity & Access Registration activate Email .");
		  
		String activateUrl=WebContext.getHttpContextPath()+"/registration/forward/activate/"+registration.getId();
		
		
		// set the html message
		String emailText="<html>";
		 			emailText+="<a href='"+activateUrl+"'>activate</a><br>";
		 			emailText+=" or copy "+activateUrl+" to brower.";
		 	   emailText+="</html>";
		email.setHtmlMsg(emailText);
		
		// set the alternative message
		email.setTextMsg("Your email client does not support HTML messages");
		
		// send the email
		email.send();
	} catch (EmailException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	  modelAndView.addObject("registered", 0); 
	return  modelAndView;
}
 
Example 12
Source File: EmailMessageSender.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public OutboundMessageResponse sendMessage( String subject, String text, String footer, User sender, Set<User> users, boolean forceSend )
{
    EmailConfiguration emailConfig = getEmailConfiguration();
    OutboundMessageResponse status = new OutboundMessageResponse();

    String errorMessage = "No recipient found";

    if ( emailConfig.getHostName() == null )
    {
        status.setOk( false );
        status.setDescription( EmailResponse.HOST_CONFIG_NOT_FOUND.getResponseMessage() );
        status.setResponseObject( EmailResponse.HOST_CONFIG_NOT_FOUND );
        return status;
    }

    String serverBaseUrl = configurationProvider.getServerBaseUrl();
    String plainContent = renderPlainContent( text, sender );
    String htmlContent = renderHtmlContent( text, footer, serverBaseUrl != null ? HOST + serverBaseUrl : "", sender );

    try
    {
        HtmlEmail email = getHtmlEmail( emailConfig.getHostName(), emailConfig.getPort(), emailConfig.getUsername(),
            emailConfig.getPassword(), emailConfig.isTls(), emailConfig.getFrom() );
        email.setSubject( getPrefixedSubject( subject ) );
        email.setTextMsg( plainContent );
        email.setHtmlMsg( htmlContent );

        boolean hasRecipients = false;

        for ( User user : users )
        {
            boolean doSend = forceSend
                || (Boolean) userSettingService.getUserSetting( UserSettingKey.MESSAGE_EMAIL_NOTIFICATION, user );

            if ( doSend && ValidationUtils.emailIsValid( user.getEmail() ) )
            {
                if ( isEmailValid( user.getEmail() ) )
                {
                    email.addBcc( user.getEmail() );
                    hasRecipients = true;

                    log.info( "Sending email to user: " + user.getUsername() + " with email address: " + user.getEmail() );
                }
                else
                {
                    log.warn( user.getEmail() + " is not a valid email for user: " + user.getUsername() );
                    errorMessage = "No valid email address found";
                }
            }
        }

        if ( hasRecipients )
        {
            email.send();

            log.info( "Email sent using host: " + emailConfig.getHostName() + ":" + emailConfig.getPort() + " with TLS: " + emailConfig.isTls() );
            status = new OutboundMessageResponse( "Email sent", EmailResponse.SENT, true );
        }
        else
        {
            status = new OutboundMessageResponse( errorMessage, EmailResponse.ABORTED, false );
        }
    }
    catch ( Exception ex )
    {
        log.error( "Error while sending email: " + ex.getMessage() + ", " + DebugUtils.getStackTrace( ex ) );
        status = new OutboundMessageResponse( "Email not sent: " + ex.getMessage(), EmailResponse.FAILED, false );
    }

    return status;
}
 
Example 13
Source File: EmailMessageSender.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public OutboundMessageResponse sendMessage( String subject, String text, Set<String> recipients )
{
    EmailConfiguration emailConfig = getEmailConfiguration();
    OutboundMessageResponse status = new OutboundMessageResponse();

    String errorMessage = "No recipient found";

    if ( emailConfig.getHostName() == null )
    {
        status.setOk( false );
        status.setDescription( EmailResponse.HOST_CONFIG_NOT_FOUND.getResponseMessage() );
        status.setResponseObject( EmailResponse.HOST_CONFIG_NOT_FOUND );
        return status;
    }

    try
    {
        HtmlEmail email = getHtmlEmail( emailConfig.getHostName(), emailConfig.getPort(), emailConfig.getUsername(),
            emailConfig.getPassword(), emailConfig.isTls(), emailConfig.getFrom() );
        email.setSubject( getPrefixedSubject( subject ) );
        email.setTextMsg( text );

        boolean hasRecipients = false;

        for ( String recipient : recipients )
        {
            if ( isEmailValid( recipient ) )
            {
                email.addBcc( recipient );
                hasRecipients = true;

                log.info( "Sending email to : " + recipient );
            }
            else
            {
                log.warn( recipient + " is not a valid email" );
                errorMessage = "No valid email address found";
            }
        }

        if ( hasRecipients )
        {
            email.send();

            log.info( "Email sent using host: " + emailConfig.getHostName() + ":" + emailConfig.getPort() + " with TLS: " + emailConfig.isTls() );
            return new OutboundMessageResponse( "Email sent", EmailResponse.SENT, true );
        }
        else
        {
            status = new OutboundMessageResponse( errorMessage, EmailResponse.ABORTED, false );
        }
    }
    catch ( Exception ex )
    {
        log.error( "Error while sending email: " + ex.getMessage() + ", " + DebugUtils.getStackTrace( ex ) );
        status = new OutboundMessageResponse( "Email not sent: " + ex.getMessage(), EmailResponse.FAILED, false );
    }

    return status;
}
 
Example 14
Source File: EmailHelper.java    From incubator-pinot with Apache License 2.0 4 votes vote down vote up
public static void sendEmailWithTextBody(HtmlEmail email, SmtpConfiguration smtpConfigutation, String subject,
    String textBody, String fromAddress, DetectionAlertFilterRecipients recipients) throws EmailException {
  email.setTextMsg(textBody);
  sendEmail(smtpConfigutation, email, subject, fromAddress, recipients);
}