org.apache.commons.mail.Email Java Examples

The following examples show how to use org.apache.commons.mail.Email. 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: 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 #2
Source File: Mail.java    From restcommander with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
public static Email buildMessage(Email email) throws EmailException {

    String from = Play.configuration.getProperty("mail.smtp.from");
    if (email.getFromAddress() == null && !StringUtils.isEmpty(from)) {
        email.setFrom(from);
    } else if (email.getFromAddress() == null) {
        throw new MailException("Please define a 'from' email address", new NullPointerException());
    }
    if ((email.getToAddresses() == null || email.getToAddresses().size() == 0) &&
        (email.getCcAddresses() == null || email.getCcAddresses().size() == 0)  &&
        (email.getBccAddresses() == null || email.getBccAddresses().size() == 0)) 
    {
        throw new MailException("Please define a recipient email address", new NullPointerException());
    }
    if (email.getSubject() == null) {
        throw new MailException("Please define a subject", new NullPointerException());
    }
    if (email.getReplyToAddresses() == null || email.getReplyToAddresses().size() == 0) {
        email.addReplyTo(email.getFromAddress().getAddress());
    }

    return email;
}
 
Example #3
Source File: MailActivityBehavior.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected void setMailServerProperties(Email email) {
  ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();

  String host = processEngineConfiguration.getMailServerHost();
  ensureNotNull("Could not send email: no SMTP host is configured", "host", host);
  email.setHostName(host);

  int port = processEngineConfiguration.getMailServerPort();
  email.setSmtpPort(port);

  email.setTLS(processEngineConfiguration.getMailServerUseTLS());

  String user = processEngineConfiguration.getMailServerUsername();
  String password = processEngineConfiguration.getMailServerPassword();
  if (user != null && password != null) {
    email.setAuthentication(user, password);
  }
}
 
Example #4
Source File: EmailService.java    From gsn with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method cover most of the cases of sending a simple text email. If the email to be sent has to be configured
 * in a way which is not possible whith the parameters provided (such as html email, or email with attachement, ..),
 * please use the {@link #sendCustomEmail(org.apache.commons.mail.Email)} method and refer the API
 * {@see http://commons.apache.org/email/}.
 *
 * @param to      A set of destination email address of the email. Must contain at least one address.
 * @param object  The subject of the email.
 * @param message The msg of the email.
 * @return true if the email has been sent successfully, false otherwise.
 */
public static boolean sendEmail(ArrayList<String> to, String object, String message) {
    Email email = new SimpleEmail();
    try {
        email.setSubject(object);
        email.setMsg(message);
        if (to != null)
            for (String _to : to)
                email.addTo(_to);
        sendCustomEmail(email);
        return true;
    }
    catch (EmailException e) {
        logger.warn("Please, make sure that the SMTP server configuration is correct in the file: " + SMTP_FILE);
        logger.error(e.getMessage(), e);
        return false;
    }
}
 
Example #5
Source File: MailActivityBehavior.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected void setFrom(Email email, String from, String tenantId) {
  String fromAddress = null;

  if (from != null) {
    fromAddress = from;
  } else { // use default configured from address in process engine config
    if (tenantId != null && tenantId.length() > 0) {
      Map<String, MailServerInfo> mailServers = Context.getProcessEngineConfiguration().getMailServers();
      if (mailServers != null && mailServers.containsKey(tenantId)) {
        MailServerInfo mailServerInfo = mailServers.get(tenantId);
        fromAddress = mailServerInfo.getMailServerDefaultFrom();
      }
    }

    if (fromAddress == null) {
      fromAddress = Context.getProcessEngineConfiguration().getMailServerDefaultFrom();
    }
  }

  try {
    email.setFrom(fromAddress);
  } catch (EmailException e) {
    throw new ActivitiException("Could not set " + from + " as from address in email", e);
  }
}
 
Example #6
Source File: ForgotPasswordController.java    From mamute with Apache License 2.0 6 votes vote down vote up
@Post
public void requestEmailWithToken(String email) {
	User user = users.loadByEmail(email);

	if (user == null) {
		validator.add(messageFactory.build("error", "forgot_password.invalid_email"));
		validator.onErrorRedirectTo(this).forgotPasswordForm();
		return;
	}

	Email forgotPasswordEmail = emailWithTokenFor(user);
	try {
		mailer.send(forgotPasswordEmail);
		result.include("mamuteMessages", Arrays.asList(
					messageFactory.build("confirmation", "forgot_password.sent_mail", user.getEmail()),
					messageFactory.build("confirmation", "forgot_password.sent_mail.warn")
				));
		result.redirectTo(this).forgotPasswordForm();
	} catch (EmailException e) {
		validator.add(messageFactory.build("error", "forgot_password.send_mail.error"));
		validator.onErrorRedirectTo(this).forgotPasswordForm();
	}	
}
 
Example #7
Source File: NewQuestionMailer.java    From mamute with Apache License 2.0 6 votes vote down vote up
public void send(List<User> subscribed, Question question) {
	linker.linkTo(QuestionController.class).showQuestion(question, question.getSluggedTitle());
	String questionLink = linker.get();
	TemplateMail template = templates.template("new_question_notification")
			.with("question", question)
			.with("bundle", bundle)
			.with("questionLink", questionLink)
			.with("logoUrl", emailLogo);
	for (User user : subscribed) {
		boolean notSameAuthor = !user.equals(question.getAuthor());
		if (notSameAuthor) {
			Email email = template.to(user.getName(), user.getEmail());
			mailer.asyncSend(email);
		}
	}
}
 
Example #8
Source File: EmailSender.java    From bobcat with Apache License 2.0 6 votes vote down vote up
public void sendEmail(final EmailData emailData) {
  try {
    Email email = new SimpleEmail();
    email.setHostName(smtpServer);
    email.setSmtpPort(smtpPort);
    email.setAuthenticator(new DefaultAuthenticator(username, password));
    email.setSSLOnConnect(secure);
    email.setFrom(emailData.getAddressFrom());
    email.setSubject(emailData.getSubject());
    email.setMsg(emailData.getMessageContent());
    email.addTo(emailData.getAddressTo());
    email.send();
  } catch (org.apache.commons.mail.EmailException e) {
    throw new EmailException(e);
  }
}
 
Example #9
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addTo(CommandContext commandContext, Email email, String to, String tenantId) {
    if (to == null) {
        // To has to be set, otherwise it can fallback to the forced To and then it won't be noticed early on
        throw new FlowableException("No recipient could be found for sending email");
    }
    String newTo = getForceTo(commandContext, tenantId);
    if (newTo == null) {
        newTo = to;
    }
    String[] tos = splitAndTrim(newTo);
    if (tos != null) {
        for (String t : tos) {
            try {
                email.addTo(t);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + t + " as recipient", e);
            }
        }
    } else {
        throw new FlowableException("No recipient could be found for sending email");
    }
}
 
Example #10
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void setFrom(CommandContext commandContext, Email email, String from, String tenantId) {
    String fromAddress = null;

    if (from != null) {
        fromAddress = from;
    } else { // use default configured from address in process engine config
        if (tenantId != null && tenantId.length() > 0) {
            Map<String, MailServerInfo> mailServers = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getMailServers();
            if (mailServers != null && mailServers.containsKey(tenantId)) {
                MailServerInfo mailServerInfo = mailServers.get(tenantId);
                fromAddress = mailServerInfo.getMailServerDefaultFrom();
            }
        }

        if (fromAddress == null) {
            fromAddress = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getMailServerDefaultFrom();
        }
    }

    try {
        email.setFrom(fromAddress);
    } catch (EmailException e) {
        throw new FlowableException("Could not set " + from + " as from address in email", e);
    }
}
 
Example #11
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addCc(CommandContext commandContext, Email email, String cc, String tenantId) {
    if (cc == null) {
        return;
    }

    String newCc = getForceTo(commandContext, tenantId);
    if (newCc == null) {
        newCc = cc;
    }
    String[] ccs = splitAndTrim(newCc);
    if (ccs != null) {
        for (String c : ccs) {
            try {
                email.addCc(c);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + c + " as cc recipient", e);
            }
        }
    }
}
 
Example #12
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addBcc(CommandContext commandContext, Email email, String bcc, String tenantId) {
    if (bcc == null) {
        return;
    }
    String newBcc = getForceTo(commandContext, tenantId);
    if (newBcc == null) {
        newBcc = bcc;
    }
    String[] bccs = splitAndTrim(newBcc);
    if (bccs != null) {
        for (String b : bccs) {
            try {
                email.addBcc(b);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + b + " as bcc recipient", e);
            }
        }
    }
}
 
Example #13
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void setFrom(Email email, String from, String tenantId) {
    String fromAddress = null;

    if (from != null) {
        fromAddress = from;
    } else { // use default configured from address in process engine config
        if (tenantId != null && tenantId.length() > 0) {
            Map<String, MailServerInfo> mailServers = Context.getProcessEngineConfiguration().getMailServers();
            if (mailServers != null && mailServers.containsKey(tenantId)) {
                MailServerInfo mailServerInfo = mailServers.get(tenantId);
                fromAddress = mailServerInfo.getMailServerDefaultFrom();
            }
        }

        if (fromAddress == null) {
            fromAddress = Context.getProcessEngineConfiguration().getMailServerDefaultFrom();
        }
    }

    try {
        email.setFrom(fromAddress);
    } catch (EmailException e) {
        throw new ActivitiException("Could not set " + from + " as from address in email", e);
    }
}
 
Example #14
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addTo(Email email, String to, String tenantId) {
    if (to == null) {
        // To has to be set, otherwise it can fallback to the forced To and then it won't be noticed early on
        throw new FlowableException("No recipient could be found for sending email");
    }
    String newTo = getForceTo(tenantId);
    if (newTo == null) {
        newTo = to;
    }
    String[] tos = splitAndTrim(newTo);
    if (tos != null) {
        for (String t : tos) {
            try {
                email.addTo(t);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + t + " as recipient", e);
            }
        }
    } else {
        throw new FlowableException("No recipient could be found for sending email");
    }
}
 
Example #15
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void setFrom(Email email, String from, String tenantId) {
    String fromAddress = null;

    if (from != null) {
        fromAddress = from;
    } else { // use default configured from address in process engine config
        if (tenantId != null && tenantId.length() > 0) {
            Map<String, MailServerInfo> mailServers = CommandContextUtil.getProcessEngineConfiguration().getMailServers();
            if (mailServers != null && mailServers.containsKey(tenantId)) {
                MailServerInfo mailServerInfo = mailServers.get(tenantId);
                fromAddress = mailServerInfo.getMailServerDefaultFrom();
            }
        }

        if (fromAddress == null) {
            fromAddress = CommandContextUtil.getProcessEngineConfiguration().getMailServerDefaultFrom();
        }
    }

    try {
        email.setFrom(fromAddress);
    } catch (EmailException e) {
        throw new FlowableException("Could not set " + from + " as from address in email", e);
    }
}
 
Example #16
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addCc(Email email, String cc, String tenantId) {
    if (cc == null) {
        return;
    }

    String newCc = getForceTo(tenantId);
    if (newCc == null) {
        newCc = cc;
    }
    String[] ccs = splitAndTrim(newCc);
    if (ccs != null) {
        for (String c : ccs) {
            try {
                email.addCc(c);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + c + " as cc recipient", e);
            }
        }
    }
}
 
Example #17
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void addBcc(Email email, String bcc, String tenantId) {
    if (bcc == null) {
        return;
    }
    String newBcc = getForceTo(tenantId);
    if (newBcc == null) {
        newBcc = bcc;
    }
    String[] bccs = splitAndTrim(newBcc);
    if (bccs != null) {
        for (String b : bccs) {
            try {
                email.addBcc(b);
            } catch (EmailException e) {
                throw new FlowableException("Could not add " + b + " as bcc recipient", e);
            }
        }
    }
}
 
Example #18
Source File: EmailManagerImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void sendVerification(final EmailConfiguration configuration, final String address) throws EmailException {
  checkNotNull(configuration);
  checkNotNull(address);

  Email mail = new SimpleEmail();
  mail.setSubject("Email configuration verification");
  mail.addTo(address);
  mail.setMsg("Verification successful");
  mail = apply(configuration, mail);
  mail.send();
}
 
Example #19
Source File: EmailUtils.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * A general method for sending emails.
 *
 * @param state a {@link State} object containing configuration properties
 * @param subject email subject
 * @param message email message
 * @throws EmailException if there is anything wrong sending the email
 */
public static void sendEmail(State state, String subject, String message) throws EmailException {
  Email email = new SimpleEmail();
  email.setHostName(state.getProp(ConfigurationKeys.EMAIL_HOST_KEY, ConfigurationKeys.DEFAULT_EMAIL_HOST));
  if (state.contains(ConfigurationKeys.EMAIL_SMTP_PORT_KEY)) {
    email.setSmtpPort(state.getPropAsInt(ConfigurationKeys.EMAIL_SMTP_PORT_KEY));
  }
  email.setFrom(state.getProp(ConfigurationKeys.EMAIL_FROM_KEY));
  if (state.contains(ConfigurationKeys.EMAIL_USER_KEY) && state.contains(ConfigurationKeys.EMAIL_PASSWORD_KEY)) {
    email.setAuthentication(state.getProp(ConfigurationKeys.EMAIL_USER_KEY),
        PasswordManager.getInstance(state).readPassword(state.getProp(ConfigurationKeys.EMAIL_PASSWORD_KEY)));
  }
  Iterable<String> tos =
      Splitter.on(',').trimResults().omitEmptyStrings().split(state.getProp(ConfigurationKeys.EMAIL_TOS_KEY));
  for (String to : tos) {
    email.addTo(to);
  }

  String hostName;
  try {
    hostName = InetAddress.getLocalHost().getHostName();
  } catch (UnknownHostException uhe) {
    LOGGER.error("Failed to get the host name", uhe);
    hostName = "unknown";
  }

  email.setSubject(subject);
  String fromHostLine = String.format("This email was sent from host: %s%n%n", hostName);
  email.setMsg(fromHostLine + message);
  email.send();
}
 
Example #20
Source File: MailService.java    From Kylin with Apache License 2.0 5 votes vote down vote up
/**
 * @param receivers
 * @param subject
 * @param content
 * @return true or false indicating whether the email was delivered successfully
 * @throws IOException
 */
public boolean sendMail(List<String> receivers, String subject, String content) throws IOException {

    if (!enabled) {
        logger.info("Email service is disabled; this mail will not be delivered: " + subject);
        logger.info("To enable mail service, set 'mail.enabled=true' in kylin.properties");
        return false;
    }

    Email email = new HtmlEmail();
    email.setHostName(host);
    if (username != null && username.trim().length() > 0) {
        email.setAuthentication(username, password);
    }

    //email.setDebug(true);
    try {
        for (String receiver : receivers) {
            email.addTo(receiver);
        }

        email.setFrom(sender);
        email.setSubject(subject);
        email.setCharset("UTF-8");
        ((HtmlEmail) email).setHtmlMsg(content);
        email.send();
        email.getMailSession();

    } catch (EmailException e) {
        logger.error(e.getLocalizedMessage(),e);
        return false;
    }

    return true;
}
 
Example #21
Source File: EmailSenderServiceTest.java    From batchers with Apache License 2.0 5 votes vote down vote up
@Test
public void givenAnEmailTO_whenSendingAnEmail_thenTheCorrectDataIsUsedAndTheEmailIsSent() throws Exception {
    EmailSenderService.EmailMapper emailMapper = new EmailSenderService.EmailMapper();

    Email email = emailMapper.mapFromEmailTO(emailTO());

    assertionsForEmail(email, emailTO());
}
 
Example #22
Source File: Mail.java    From restcommander with Apache License 2.0 5 votes vote down vote up
/**
 * Send an email
 */
public static Future<Boolean> send(Email email) {
    try {
        email = buildMessage(email);

        if (Play.configuration.getProperty("mail.smtp", "").equals("mock") && Play.mode == Play.Mode.DEV) {
            Mock.send(email);
            return new Future<Boolean>() {

                public boolean cancel(boolean mayInterruptIfRunning) {
                    return false;
                }

                public boolean isCancelled() {
                    return false;
                }

                public boolean isDone() {
                    return true;
                }

                public Boolean get() throws InterruptedException, ExecutionException {
                    return true;
                }

                public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
                    return true;
                }
            };
        }

        email.setMailSession(getSession());
        return sendMessage(email);
    } catch (EmailException ex) {
        throw new MailException("Cannot send email", ex);
    }
}
 
Example #23
Source File: MailActivityBehavior.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void execute(ActivityExecution execution) {
  String toStr = getStringFromField(to, execution);
  String fromStr = getStringFromField(from, execution);
  String ccStr = getStringFromField(cc, execution);
  String bccStr = getStringFromField(bcc, execution);
  String subjectStr = getStringFromField(subject, execution);
  String textStr = getStringFromField(text, execution);
  String htmlStr = getStringFromField(html, execution);
  String charSetStr = getStringFromField(charset, execution);

  Email email = createEmail(textStr, htmlStr);

  addTo(email, toStr);
  setFrom(email, fromStr);
  addCc(email, ccStr);
  addBcc(email, bccStr);
  setSubject(email, subjectStr);
  setMailServerProperties(email);
  setCharset(email, charSetStr);

  try {
    email.send();
  } catch (EmailException e) {
    throw LOG.sendingEmailException(toStr, e);
  }
  leave(execution);
}
 
Example #24
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void addTo(Email email, String to) {
    String[] tos = splitAndTrim(to);
    if (tos != null) {
        for (String t : tos) {
            try {
                email.addTo(t);
            } catch (EmailException e) {
                throw new ActivitiException("Could not add " + t + " as recipient", e);
            }
        }
    } else {
        throw new ActivitiException("No recipient could be found for sending email");
    }
}
 
Example #25
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected Email createEmail(String text, String html, boolean attachmentsExist) {
    if (html != null) {
        return createHtmlEmail(text, html);
    } else if (text != null) {
        if (!attachmentsExist) {
            return createTextOnlyEmail(text);
        } else {
            return createMultiPartEmail(text);
        }
    } else {
        throw new ActivitiIllegalArgumentException("'html' or 'text' is required to be defined when using the mail activity");
    }
}
 
Example #26
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void setEmailSession(Email email, String mailSessionJndi) {
    try {
        email.setMailSessionFromJNDI(mailSessionJndi);
    } catch (NamingException e) {
        throw new FlowableException("Could not send email: Incorrect JNDI configuration", e);
    }
}
 
Example #27
Source File: MockEmailConcrete.java    From commons-email with Apache License 2.0 5 votes vote down vote up
/**
 * Not Implemented, should be implemented in subclasses of Email
 * @param msg The email message
 * @return Email msg.
 */
@Override
public Email setMsg(final String msg)
{
    // This abstract method should be tested in the concrete
    // implementation classes only.
    return null;
}
 
Example #28
Source File: MailTest.java    From restcommander with Apache License 2.0 5 votes vote down vote up
@Test(expected = MailException.class)
public void buildMessageWithoutRecipient() throws EmailException {
	new PlayBuilder().build();

	Email email = new SimpleEmail();
	email.setFrom("[email protected]");
	email.setSubject("subject");
	Mail.buildMessage(email);
}
 
Example #29
Source File: MailActivityBehavior.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected void addBcc(Email email, String bcc) {
  String[] bccs = splitAndTrim(bcc);
  if (bccs != null) {
    for (String b : bccs) {
      try {
        email.addBcc(b);
      } catch (EmailException e) {
        throw LOG.addBccException(b, e);
      }
    }
  }
}
 
Example #30
Source File: MailActivityBehavior.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void addBcc(Email email, String bcc) {
    String[] bccs = splitAndTrim(bcc);
    if (bccs != null) {
        for (String b : bccs) {
            try {
                email.addBcc(b);
            } catch (EmailException e) {
                throw new ActivitiException("Could not add " + b + " as bcc recipient", e);
            }
        }
    }
}