Java Code Examples for org.apache.commons.mail.HtmlEmail

The following are top voted examples for showing how to use org.apache.commons.mail.HtmlEmail. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: selenium-testng-template   File: SendEmailReporter.java   View source code 7 votes vote down vote up
private void sendEmail(String content) throws Exception {
	System.out.println("Send Email:");
	if (!Config.getBoolean("email.enabled")) {
		return;
	}
	
	HtmlEmail email = new HtmlEmail();
	for (String receipt : Config.getArrayProperty("report.email.recipients")) {
		email.addTo(receipt);
	}
	email.setFrom(Config.getProperty("report.email.from"));
	email.setSubject(Config.getProperty("report.email.subject"));
	email.setHtmlMsg(content);
	email.setHostName(Config.getProperty("report.email.host"));
	email.setAuthentication(Config.getProperty("report.email.username"), 
			Config.getProperty("report.email.password"));
	email.send();
}
 
Example 2
Project: exam   File: EmailSenderImpl.java   View source code 7 votes vote down vote up
private void doSend(String recipient, String sender, Set<String> cc, String subject, String content,
                    EmailAttachment... attachments) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setCharset("utf-8");
    for (EmailAttachment attachment : attachments) {
        email.attach(attachment);
    }
    email.setHostName(HOST);
    email.setSmtpPort(PORT);
    email.setAuthenticator(new DefaultAuthenticator(USER, PWD));
    email.setSSLOnConnect(USE_SSL);
    email.setSubject(subject);
    email.addTo(recipient);
    email.setFrom(String.format("Exam <%s>", SYSTEM_ACCOUNT));
    email.addReplyTo(sender);
    for (String addr : cc) {
        email.addCc(addr);
    }
    email.setHtmlMsg(content);
    if (USE_MOCK) {
        mockSending(email, content, attachments);
    } else {
        email.send();
    }
}
 
Example 3
Project: OSCAR-ConCert   File: EmailUtilsOld.java   View source code 7 votes vote down vote up
/**
 * This main method is useful when debugging smtp configuration problems.
 */
public static void main(String... argv) throws EmailException
{
		// gmail : smtp.gmail.com:465		
	
		String fromEmailAddress=argv[0];
		String toEmailAddress=argv[1];
		String smtpServer=argv[2];
		
		String smtpPort=(argv.length>3?argv[3]:null);
		String smtpUser=(argv.length>4?argv[4]:null);
		String smtpPassword=(argv.length>5?argv[4]:null);
                       String connectionSecurity=(argv.length>6?argv[5]:null);
		HtmlEmail htmlEmail=EmailUtilsOld.getHtmlEmail(smtpServer, smtpPort, smtpUser, smtpPassword, connectionSecurity);

		htmlEmail.addTo(toEmailAddress, toEmailAddress);
		htmlEmail.setFrom(fromEmailAddress, fromEmailAddress);

		htmlEmail.setSubject("test subject");
		htmlEmail.setTextMsg("test contents "+(new java.util.Date()));

		htmlEmail.send();
}
 
Example 4
Project: OSCAR-ConCert   File: Log4JGmailExecutorTask.java   View source code 7 votes vote down vote up
private void sendEmail() throws EmailException
{
	HtmlEmail email = new HtmlEmail();
	email.setHostName(smtpServer);
	if (smtpUser != null && smtpPassword != null) email.setAuthentication(smtpUser, smtpPassword);

	if (smtpSslPort != null)
	{
		email.setSSL(true);
		email.setSslSmtpPort(smtpSslPort);
	}

	Session session = email.getMailSession();
	Properties properties = session.getProperties();
	properties.setProperty("mail.smtp.connectiontimeout", "20000");
	properties.setProperty("mail.smtp.timeout", "20000");

	email.addTo(recipientEmailAddress, recipientEmailAddress);
	email.setFrom(smtpUser, smtpUser);

	email.setSubject(subject);
	email.setHtmlMsg(contents);
	email.setTextMsg(contents);
	email.send();
}
 
Example 5
Project: MBLive   File: MailKit.java   View source code 7 votes vote down vote up
public static void send(Mail mail) {
    HtmlEmail email = new HtmlEmail();
    try {
        email.setHostName(mail.getHost());
        email.setCharset(Config.UTF_8);
        email.addTo(mail.getReceiver());
        email.setFrom(mail.getSender(), mail.getName());
        email.setAuthentication(mail.getUsername(), mail.getPassword());
        email.setSubject(mail.getSubject());
        email.setMsg(mail.getMessage());
        email.setSmtpPort(mail.getSmtpPort());
        email.send();
    } catch (EmailException e) {
        e.printStackTrace();
    }
}
 
Example 6
Project: Shop-for-JavaWeb   File: SendMailUtil.java   View source code 7 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 7
Project: H-Viewer   File: EmailUtil.java   View source code 7 votes vote down vote up
public static void sendMailByApache(String to, String title, String content) {

        try {
            HtmlEmail email = new HtmlEmail();
            // 这里是发送服务器的名字
            email.setHostName(smtpHost);
            // 编码集的设置
            email.setTLS(true);
            email.setSSL(true);

            email.setCharset("utf-8");
            // 收件人的邮箱
            email.addTo(to);
            // 发送人的邮箱
            email.setFrom(fromEmail);
            // 如果需要认证信息的话,设置认证:用户名-密码。分别为发件人在邮件服务器上的注册名称和密码
            email.setAuthentication(username, password);
            email.setSubject(title);
            // 要发送的信息
            email.setMsg(content);
            // 发送
            email.send();
        } catch (EmailException e) {
            Log.i("EmailUtil", e.getMessage());
        }
    }
 
Example 8
Project: dhis2-core   File: EmailMessageSender.java   View source code 7 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, customizeTitle( DEFAULT_FROM_NAME ) );
    email.setSmtpPort( port );
    email.setStartTLSEnabled( tls );

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

    return email;
}
 
Example 9
Project: example-java   File: EmailExample.java   View source code 7 votes vote down vote up
/**
 * send mail
 */
@Test
public void test() {
    try {
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setHostName("smtp.qq.com");
        htmlEmail.setFrom("[email protected]", "[email protected]");
        htmlEmail.addTo("[email protected]");
        htmlEmail.addCc("[email protected]", "[email protected]");
        htmlEmail.setAuthentication("[email protected]", "TaylorSwift");
        htmlEmail.setSubject("email example");
        htmlEmail.setHtmlMsg("test apache email");
        htmlEmail.setCharset("UTF-8");
        htmlEmail.buildMimeMessage();
        htmlEmail.sendMimeMessage();
    } catch (EmailException e) {
        System.out.println(e.getMessage());
    }
}
 
Example 10
Project: AgileAlligators   File: EmailMessageSender.java   View source code 7 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( defaultIfEmpty( sender, FROM_ADDRESS ), customizeTitle( DEFAULT_FROM_NAME ) );
    email.setSmtpPort( port );
    email.setStartTLSEnabled( tls );

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

    return email;
}
 
Example 11
Project: commons-test   File: MockSMTPServerTest.java   View source code 7 votes vote down vote up
@Test
public void testSendEmail() throws Exception {
	MockSMTPServer server = new MockSMTPServer();
	assertFalse(server.isRunning());
	server.start();
	assertTrue(server.isRunning());
	int port = server.getPort();
	assertTrue(port > 0);

	HtmlEmail email = new HtmlEmail();
	email.setHostName("localhost");
	email.setSmtpPort(port);

	email.setTextMsg("somemessage");
	email.setSubject("somesubj");
	email.setTo(Arrays.asList(InternetAddress.parse("[email protected]")));
	email.setFrom("[email protected]");

	email.send();

	assertEquals(1, server.getMessageCount());
	assertNotNull(server.getMessages());
	assertNotNull(server.getMessages().next());

	server.stop();
}
 
Example 12
Project: email-api   File: EmailSendingHealthCheck.java   View source code 7 votes vote down vote up
@Override
protected Result check() throws Exception {
    try {
        HtmlEmail testEmail = htmlEmailFactory.getHtmlEmail();
        testEmail.setMsg("Testing");
        testEmail.setSubject("Testing");
        testEmail.setFrom("[email protected]");

        final InternetAddress testToAddress = new InternetAddress("[email protected]");
        ArrayList<InternetAddress> toAddresses = new ArrayList<>();
        toAddresses.add(testToAddress);

        testEmail.setTo(toAddresses);
        testEmail.send();

        return Result.healthy();
    } catch (Exception e) {
        return Result.unhealthy(e);
    }
}
 
Example 13
Project: TechnologyReadinessTool   File: EmailServiceImpl.java   View source code 7 votes vote down vote up
@Override
public void sendHtmlAndTextEmail(String to, String subject, String htmlBody, String textBody) throws ServiceException {
	HtmlEmail email = new HtmlEmail();

	try {
		setupEmail(email);
		validateAddress(to);
		email.addTo(to);
		email.setSubject(subject);
		email.setHtmlMsg(htmlBody);
		email.setTextMsg(textBody);
		email.send();
	} catch (EmailException e) {
		log.error("ZZZ.EmailException. To: " + to + " Subject: " + subject, e);
		throw new ServiceException("Unable to send email.", e);
	}
}
 
Example 14
Project: TechnologyReadinessTool   File: EmailServiceImpl.java   View source code 7 votes vote down vote up
@Override
public void sendHtmlEmail(String to, String subject, String htmlBody) throws ServiceException {
	HtmlEmail email = new HtmlEmail();

	try {
		setupEmail(email);
		validateAddress(to);
		email.addTo(to);
		email.setSubject(subject);
		email.setHtmlMsg(htmlBody);
		email.send();
	} catch (EmailException e) {
		log.error("ZZZ.EmailException. To: " + to + " Subject: " + subject, e);
		throw new ServiceException("Unable to send email.", e);
	}
}
 
Example 15
Project: ShipworksWeeklyReports   File: Email.java   View source code 7 votes vote down vote up
public void sendEmail() {
	HtmlEmail email = new HtmlEmail();
	try {
		email.setHostName(emailHostName);
		email.setSmtpPort(smtpPort);
		email.setAuthenticator(new DefaultAuthenticator(emailLogin,
				emailPassword));
		email.setSSLOnConnect(emailSSL);
		email.setStartTLSEnabled(startTLS);
		email.setFrom(emailSender);
		email.setSubject(title);
		email.setHtmlMsg(htmlMessage);
		email.addTo(emailRecipient);
		email.send();
		System.out.println("Email sent: " + title);
	} catch (EmailException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 16
Project: pinot   File: EmailHelper.java   View source code 7 votes vote down vote up
/** Sends email according to the provided config. */
private static void sendEmail(SmtpConfiguration config, HtmlEmail email, String subject,
    String fromAddress, String toAddress) throws EmailException {
  if (config != null) {
    email.setSubject(subject);
    LOG.info("Sending email to {}", toAddress);
    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);
    for (String address : toAddress.split(EMAIL_ADDRESS_SEPARATOR)) {
      email.addTo(address);
    }
    email.send();
    LOG.info("Email sent with subject [{}] to address [{}]!", subject, toAddress);
  } else {
    LOG.error("No email config provided for email with subject [{}]!", subject);
  }
}
 
Example 17
Project: clobaframe   File: SmtpMailSender.java   View source code 7 votes vote down vote up
@Override
public void sendWithHtml(String recipient, String subject, String content) throws SendMailException {
	Assert.hasText(recipient);
	Assert.hasText(subject);
	Assert.hasText(content);
	
	HtmlEmail email = new HtmlEmail();
	email.setHostName(host);
	email.setAuthenticator(new DefaultAuthenticator(loginName, loginPassword));
	email.setSmtpPort(port);
	email.setTLS(tls);

	try {
		email.setCharset("UTF-8"); // specify the charset.
		email.setFrom(fromAddress, fromName);
		email.setSubject(subject);
		email.setHtmlMsg(content);
		//email.setMsg(""); // can set plain text either
		email.addTo(recipient);
		email.send();
	} catch (EmailException e) {
		throw new SendMailException(
				String.format("Failed to send mail to %s.", recipient), e);
	}
}
 
Example 18
Project: oscar-old   File: EmailUtils.java   View source code 7 votes vote down vote up
/**
 * This main method is useful when debugging smtp configuration problems.
 */
public static void main(String... argv) throws EmailException
{
		// gmail : smtp.gmail.com:465		
	
		String fromEmailAddress=argv[0];
		String toEmailAddress=argv[1];
		String smtpServer=argv[2];
		
		String smtpPort=(argv.length>3?argv[3]:null);
		String smtpUser=(argv.length>4?argv[4]:null);
		String smtpPassword=(argv.length>5?argv[4]:null);
                       String connectionSecurity=(argv.length>6?argv[5]:null);
		HtmlEmail htmlEmail=EmailUtils.getHtmlEmail(smtpServer, smtpPort, smtpUser, smtpPassword, connectionSecurity);

		htmlEmail.addTo(toEmailAddress, toEmailAddress);
		htmlEmail.setFrom(fromEmailAddress, fromEmailAddress);

		htmlEmail.setSubject("test subject");
		htmlEmail.setTextMsg("test contents "+(new java.util.Date()));

		htmlEmail.send();
}
 
Example 19
Project: oscar-old   File: Log4JGmailExecutorTask.java   View source code 7 votes vote down vote up
private void sendEmail() throws EmailException
{
	HtmlEmail email = new HtmlEmail();
	email.setHostName(smtpServer);
	if (smtpUser != null && smtpPassword != null) email.setAuthentication(smtpUser, smtpPassword);

	if (smtpSslPort != null)
	{
		email.setSSL(true);
		email.setSslSmtpPort(smtpSslPort);
	}

	Session session = email.getMailSession();
	Properties properties = session.getProperties();
	properties.setProperty("mail.smtp.connectiontimeout", "20000");
	properties.setProperty("mail.smtp.timeout", "20000");

	email.addTo(recipientEmailAddress, recipientEmailAddress);
	email.setFrom(smtpUser, smtpUser);

	email.setSubject(subject);
	email.setHtmlMsg(contents);
	email.setTextMsg(contents);
	email.send();
}
 
Example 20
Project: AisAbnormal   File: ReportMailer.java   View source code 7 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 21
Project: scoutmaster   File: SMTPSettingsDao.java   View source code 7 votes vote down vote up
private void addEmailAddress(final HtmlEmail email, final String firstAddress, final EmailAddressType firstType)
		throws EmailException
{
	switch (firstType)
	{
		case To:
			email.addTo(firstAddress);
			break;
		case BCC:
			email.addBcc(firstAddress);
			break;
		case CC:
			email.addCc(firstAddress);
			break;
	}
}
 
Example 22
Project: feed-buddy   File: SendEmail.java   View source code 7 votes vote down vote up
@Override
public void process(Item item, Logger logger) throws ItemHandlerException {

	HtmlEmail email = new HtmlEmail();

	try {
		email.addTo(to);
		setFrom(email, item);
		setSentDate(email, item, logger);
		email.setSubject(item.getTitle());
		email.setHtmlMsg(getHtmlMsg(item));
		email.setMailSession(getMailSession());
		email.send();
	}
	catch (Exception e) {
		throw new ItemHandlerException("Could not send email", e);
	}

	logger.log("Sent item email to " + to);
}
 
Example 23
Project: shepher   File: GeneralMailSender.java   View source code 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 24
Project: displaydirect   File: EmailUtil.java   View source code 6 votes vote down vote up
public static void sendHtmlEmail(String to, String subject, String template, Map<String, Object> variables) {

        try {
            final HtmlEmail email = new HtmlEmail();
            setupEmail(email, to, subject, template, variables);
            email.setHtmlMsg(EmailUtil.getHtmlBody(template, variables));
            email.setTextMsg(EmailUtil.getTextBody(template, variables));
            email.setSocketConnectionTimeout(Configuration.getSmtpConnectTimeout());

            email.send();
        } catch (Exception e) {
            LOGGER.error("Error sending HTML email", e);
        }
    }
 
Example 25
Project: Gargoyle   File: MimeConverter.java   View source code 6 votes vote down vote up
@Test
public void simple() throws Exception {

	new ProxyInitializable().initialize();

	HtmlEmail email = new HtmlEmail();
	email.setHostName("mail.myserver.com");
	email.addTo("[email protected]", "John Doe");
	// email.setFrom("[email protected]", "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();
}
 
Example 26
Project: leopard   File: MailClientImpl.java   View source code 6 votes vote down vote up
@Override
public boolean sendHtml(String to, String subject, String content) throws EmailException {
	HtmlEmail email = new HtmlEmail();
	email.setHostName(host);// 设置使用发电子邮件的邮件服务器
	email.addTo(to);
	email.setAuthentication(user, password);
	email.setFrom(user);
	email.setSubject(subject);
	email.setMsg(content);
	email.setSSLOnConnect(true);
	email.setSslSmtpPort("465"); // 若启用,设置smtp协议的SSL端口号
	email.send();
	return true;
}
 
Example 27
Project: OSCAR-ConCert   File: EmailUtilsOld.java   View source code 6 votes vote down vote up
/**
 * This is a convenience method for sending and email to 1 recipient using the configuration file settings.
 * @throws EmailException 
 */
public static void sendEmail(String toEmailAddress, String toName, String fromEmailAddress, String fromName, String subject, String textContents, String htmlContents) throws EmailException
{
	HtmlEmail htmlEmail = getHtmlEmail();

	htmlEmail.addTo(toEmailAddress, toName);
	htmlEmail.setFrom(fromEmailAddress, fromName);

	htmlEmail.setSubject(subject);
	if (textContents != null) htmlEmail.setTextMsg(textContents);
	if (htmlContents != null) htmlEmail.setHtmlMsg(htmlContents);

	//htmlEmail.getMailSession().setDebug(true);
	htmlEmail.send();
}
 
Example 28
Project: imgate   File: SendMailMain.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName("smtp.example.com");
    email.setFrom("[email protected]", "From User");
    email.addTo("[email protected]", "To User");
    email.addTo("[email protected]", "To 2 User");
    email.addCc("[email protected]", "CC User");
    email.addBcc("[email protected]", "BCC User");
    email.setSubject("Sample Email Subject");
    email.setMsg("<p>This is body content.</p>");
    email.send();
}
 
Example 29
Project: sosoapi-base   File: ApacheMailServiceImpl.java   View source code 6 votes vote down vote up
private void sendHtmlMail(String fromEmail, String fromPasswd,String fromName,
		String host,List<String> toEmailList,MailMsg mailMsg){
	HtmlEmail email = new HtmlEmail();
	try {
    	initEmail(email, fromEmail, fromPasswd, fromName,host, toEmailList, mailMsg);
		email.setHtmlMsg(mailMsg.getContent());
    	email.send();
    } 
    catch (EmailException e) {
    	e.printStackTrace();
    }
}
 
Example 30
Project: sorcerer   File: Emailer.java   View source code 6 votes vote down vote up
private void sendEmail() throws EmailException, UnknownHostException {

		List<String> addresses =
				Lists.newArrayList(Splitter.on(',')
						.omitEmptyStrings()
						.trimResults()
						.split(ADMIN_EMAIL.getAdmins()));
		logger.info("Sending email to {}", addresses.toString());


		Email email = new HtmlEmail();
		email.setHostName(ADMIN_EMAIL.getHost());
		email.setSocketTimeout(30000); // 30 seconds
		email.setSocketConnectionTimeout(30000); // 30 seconds
		for (String address : addresses) {
			email.addTo(address);
		}
		email.setFrom(SorcererInjector.get().getModule().getName() + "@" +
				InetAddress.getLocalHost().getHostName());
		email.setSubject(title);
		email.setMsg(body);
		email.send();

	}
 
Example 31
Project: actionbazaar   File: EmailService.java   View source code 6 votes vote down vote up
/**
 * Sends out an email
 * @param message - message to be sent
 */
public void onMessage(Message message) {

    try {
        EmailRequest emailRequest = (EmailRequest)((ObjectMessage)message).getObject();
        
        Query query = entityManager.createQuery("select e from Email e where e.action = ?1");
        query.setParameter(1,emailRequest.getAction());
        List results = query.getResultList();
        if(results.size() != 1) {
            logger.severe("A total of " + results.size() + " email templates were returned for action " +
                    emailRequest.getAction());
            return;
        }
        System.out.println("--> Sending email.");
        Email emailInfo = (Email)results.get(0);
        logger.info("Speaker Directory: " + attachmentDirectory);
        HtmlEmail email = new HtmlEmail();
        email.setMailSession(mailSession);
        email.setTextMsg("Hello World!");
      //  email.setSubject(template.getSubject());
        email.addTo("[email protected]");
        email.setFrom("[email protected]");
      //  email.send();
        
 /*       emailTemplate.process(emailRecipient.getReplacementTokens());
                    for (Map.Entry<String,File> entry : emailTemplate.getCidMappings().entrySet()) {
                        email.embed(entry.getValue(),entry.getKey());
                    }
                    email.setHtmlMsg(emailTemplate.getPatchedEmail());
   */
    } catch(Throwable t) {
        t.printStackTrace();
        //context.setRollbackOnly();
    }
}
 
Example 32
Project: mangooio   File: Mail.java   View source code 6 votes vote down vote up
private void sendHtmlEmail() throws MangooMailerException {
    Config config = Application.getInstance(Config.class);
    try {
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset(Default.ENCODING.toString());
        htmlEmail.setHostName(config.getSmtpHost());
        htmlEmail.setSmtpPort(config.getSmtpPort());
        htmlEmail.setAuthenticator(getDefaultAuthenticator());
        htmlEmail.setSSLOnConnect(config.isSmtpSSL());
        htmlEmail.setFrom(this.from);
        htmlEmail.setSubject(this.subject);
        htmlEmail.setHtmlMsg(render());
        
        for (String recipient : this.recipients) {
            htmlEmail.addTo(recipient);
        }
        
        for (String cc : this.ccRecipients) {
            htmlEmail.addCc(cc);
        }
        
        for (String bcc : this.bccRecipients) {
            htmlEmail.addBcc(bcc);
        }
        
        for (File file : this.files) {
            htmlEmail.attach(file);
        }
        
        htmlEmail.send();
    } catch (EmailException | MangooTemplateEngineException e) {
        throw new MangooMailerException(e);
    } 
}
 
Example 33
Project: email-api   File: HtmlEmailFactoryImpl.java   View source code 6 votes vote down vote up
public HtmlEmail getHtmlEmail() {
    HtmlEmail email = new HtmlEmail();

    email.setHostName(hostname);
    email.setSmtpPort(port);

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

    email.setSSLOnConnect(sslOnConnect);
    email.setStartTLSEnabled(startTslEnabled);
    email.setStartTLSRequired(requireTsl);

    return email;
}
 
Example 34
Project: email-api   File: TemplatedEmailFactoryImpl.java   View source code 6 votes vote down vote up
public HtmlEmail build(final TemplatedEmail templatedEmail)
    throws EmailException, TemplatePopulatorParsingException, TemplatePopulatorIOException,
    InternetAddressParsingException {

    HtmlEmail email = htmlEmailFactory.getHtmlEmail();

    final Collection<InternetAddress> recipients =
        addressParser.getInternetAddresses(templatedEmail.getRecipients());
    email.setTo(recipients);

    try {
        email.setFrom(templatedEmail.getSender());
    } catch (EmailException e) {
        throw new InternetAddressParsingException(e);
    }

    email.setSubject(templatedEmail.getSubject());

    String htmlProcessedTemplate = templateEngine
        .populateTemplate(templatedEmail.getHtmlTemplate(), templatedEmail.getVariables());
    email.setHtmlMsg(htmlProcessedTemplate);

    final String txtProcessedTemplate = templateEngine
        .populateTemplate(templatedEmail.getTextTemplate(), templatedEmail.getVariables());
    email.setTextMsg(txtProcessedTemplate);

    return email;
}
 
Example 35
Project: email-api   File: TemplatedEmailFactoryImplTest.java   View source code 6 votes vote down vote up
@Before
public void setupSubject() throws InternetAddressParsingException {
    templatePopulator = mock(TemplatePopulator.class);

    internetAddresses = new ArrayList<>();

    final InternetAddressParser internetAddressParser = mock(InternetAddressParser.class);
    when(internetAddressParser.getInternetAddresses(Matchers.<Collection<String>>any()))
        .thenReturn(internetAddresses);


    final HtmlEmailFactory htmlEmailFactory = mock(HtmlEmailFactory.class);
    when(htmlEmailFactory.getHtmlEmail()).thenReturn(mock(HtmlEmail.class, CALLS_REAL_METHODS));

    templatedEmailFactory =
        new TemplatedEmailFactoryImpl(templatePopulator, internetAddressParser,
            htmlEmailFactory);
}
 
Example 36
Project: email-api   File: TemplatedEmailFactoryImplTest.java   View source code 6 votes vote down vote up
@Test
public void testItSetsFrom() throws Exception {
    when(templatePopulator
        .populateTemplate(Matchers.<String>any(), Matchers.<Map<String, Object>>any()))
        .thenReturn(TEMPLATE_CONTENTS);

    internetAddresses.add(new InternetAddress("[email protected]"));

    TemplatedEmail input =
        new TemplatedEmailImpl(new ArrayList<>(), "[email protected]", "Subject",
            "html template", new HashMap<>(), "text template");
    HtmlEmail output = templatedEmailFactory.build(input);
    InternetAddress expected = new InternetAddress("[email protected]");

    assertThat(output.getFromAddress(), equalTo(expected));
}
 
Example 37
Project: translationstudio8   File: MailSender.java   View source code 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 38
Project: scale.commons   File: TestSmtpSender.java   View source code 6 votes vote down vote up
/**
 * Test sending an {@link HtmlEmail}.
 */
@Test
public void sendHtmlEmail() throws Exception {
    assertThat(this.sslMailServer.getReceivedMessages().length, is(0));

    HtmlEmail email = new HtmlEmail();
    email.setFrom("[email protected]");
    email.setSubject("subject");
    email.setHtmlMsg("<h1>Hi</h1>\nHope you're doing well.");
    email.setTextMsg("Hi! Your mail client doesn't seem to support HTML.");
    email.addTo("[email protected]");
    email.setSentDate(UtcTime.now().toDate());
    SmtpSender sender = new SmtpSender(email, new SmtpClientConfig("localhost", SMTP_SSL_PORT,
            new SmtpClientAuthentication(USERNAME, PASSWORD), true));
    sender.call();

    // check mailbox after sending
    MimeMessage[] receivedMessages = this.sslMailServer.getReceivedMessages();
    assertThat(receivedMessages.length, is(1));
    assertThat(receivedMessages[0].getSubject(), is("subject"));
    assertThat(receivedMessages[0].getSentDate(), is(FrozenTime.now().toDate()));
    MimeMessage message = receivedMessages[0];
    Object content = message.getContent();
    assertThat(content, instanceOf(MimeMultipart.class));
    MimeMultipart mimeContent = (MimeMultipart) content;
    Object firstPart = mimeContent.getBodyPart(0).getContent();
    Object secondPart = mimeContent.getBodyPart(1).getContent();
    assertThat(firstPart, is("Hi! Your mail client doesn't seem to support HTML."));
    assertThat(secondPart, is("<h1>Hi</h1>\r\nHope you're doing well."));
}
 
Example 39
Project: scale.commons   File: HtmlWithEmbeddedRemoteImageSmtpSenderLab.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    HtmlEmail email = new HtmlEmail();
    for (String recipient : RECIPIENTS) {
        email.addTo(recipient);
    }
    email.setFrom("[email protected]", "Elastisys Testing");
    email.setSubject("Test mail");
    // embed a remote image and get the content id
    String cid = email.embed(new File("src/test/resources/img/elastisys-logo.png"), "image");
    email.setHtmlMsg("<html><img height=200 src=\"cid:" + cid + "\"/><h1>Congratulations</h1>" + "\n"
            + "You are our one millionth customer!</html>");

    SmtpSender requester = new SmtpSender(email,
            new SmtpClientConfig(MAIL_SERVER, MAIL_PORT, AUTH, USE_SSL, 5000, 5000));

    System.out.println("sending email ...");
    requester.call();
    System.out.println("done.");
}
 
Example 40
Project: scale.commons   File: HtmlWithEmbeddedLocalImageSmtpSenderLab.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    HtmlEmail email = new HtmlEmail();
    for (String recipient : RECIPIENTS) {
        email.addTo(recipient);
    }
    email.setFrom("[email protected]", "Elastisys Testing");
    email.setSubject("Test mail");
    // embed a remote image and get the content id
    URL url = new URL("https://upload.wikimedia.org/wikipedia/commons/f/f4/Alfred_Nobel.png");
    String cid = email.embed(url, "image");
    email.setHtmlMsg("<html><img src=\"cid:" + cid + "\"/><h1>Congratulations</h1>" + "\n"
            + "You have just won the nobel prize!</html>");

    SmtpSender requester = new SmtpSender(email,
            new SmtpClientConfig(MAIL_SERVER, MAIL_PORT, AUTH, USE_SSL, 5000, 5000));

    System.out.println("sending email ...");
    requester.call();
    System.out.println("done.");
}