Java Code Examples for org.apache.commons.mail.Email#addTo()

The following examples show how to use org.apache.commons.mail.Email#addTo() . These examples are extracted from open source projects. 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: shepher   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 2
Source Project: bobcat   File: EmailSender.java    License: 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 3
Source Project: MaxKey   File: MailTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test() throws Exception {
String username="[email protected]";
String password="3&8Ujbnm5hkjhFD";
String smtpHost="smtp.exmail.qq.com";
int port=465;
boolean ssl=true;
String senderMail="[email protected]";

Email email = new SimpleEmail();
email.setHostName(smtpHost);
email.setSmtpPort(port);
email.setAuthenticator(new DefaultAuthenticator(username, password));
email.setSSLOnConnect(ssl);
email.setFrom(senderMail);
email.setSubject("One Time PassWord");
email.setMsg("You Token is "+111+" , it validity in "+5 +" minutes");
email.addTo("[email protected]");
email.send();
}
 
Example 4
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 5
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 6
Source Project: gsn   File: EmailService.java    License: 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 7
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 8
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 9
Source Project: MaxKey   File: MailOtpAuthn.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean produce(UserInfo userInfo) {
    try {
        String token = this.genToken(userInfo);
        Email email = new SimpleEmail();
        email.setHostName(emailConfig.getSmtpHost());
        email.setSmtpPort(emailConfig.getPort());
        email.setSSLOnConnect(emailConfig.isSsl());
        email.setAuthenticator(
                new DefaultAuthenticator(emailConfig.getUsername(), emailConfig.getPassword()));
        
        email.setFrom(emailConfig.getSender());
        email.setSubject(subject);
        email.setMsg(
                MessageFormat.format(
                        messageTemplate,userInfo.getUsername(),token,(interval / 60)));
        
        email.addTo(userInfo.getEmail());
        email.send();
        _logger.debug(
                "token " + token + " send to user " + userInfo.getUsername() 
                + ", email " + userInfo.getEmail());
        //成功返回
        this.optTokenStore.store(
                userInfo, 
                token, 
                userInfo.getMobile(), 
                OptTypes.EMAIL);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 10
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 11
private void sendEmail(final String subject, final String address, final String body) {
  try {
    Email mail = new SimpleEmail();
    mail.setSubject(subject);
    mail.addTo(address);
    mail.setMsg(body);
    emailManager.get().send(mail);
  }
  catch (Exception e) {
    log.warn("Failed to send email", e);
  }
}
 
Example 12
@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 13
@Async
public void send(EmailDetails details) {
    if (details.getSubject() == null || !BooleanUtils.xor(ArrayUtils.toArray(details.getMessage() != null, details.getMessageTemplate() != null))) {
        throw new IllegalStateException("Either subject or subjectKey / either template/message/messageKey should be specified");
    }
    Validate.notBlank(details.getFrom());

    Email email = createEmail(details.isHtml());
    String subject = constructSubject(details);
    email.setSubject(subject);

    String emailMessage = constructEmailMessages(details);

    try {
        if (details.isHtml()) {
            ((HtmlEmail) email).setHtmlMsg(emailMessage);
        } else {
            email.setMsg(emailMessage);
        }

        for (String to : details.getTo()) {
            email.addTo(to);
        }
        email.setFrom(details.getFrom());

        email.send();
    } catch (EmailException ex) {
        logger.error("Exception occurred when sending email to " + details.getTo(), ex);
    }
}
 
Example 14
Source Project: incubator-gobblin   File: EmailUtils.java    License: 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 15
Source Project: Kylin   File: MailService.java    License: 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 16
Source Project: restcommander   File: MailTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = MailException.class)
public void buildMessageWithoutFrom() throws EmailException {
	new PlayBuilder().build();

	Email email = new SimpleEmail();
	email.addTo("[email protected]");
	email.setSubject("subject");
	Mail.buildMessage(new SimpleEmail());
}
 
Example 17
Source Project: restcommander   File: MailTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = MailException.class)
public void buildMessageWithoutSubject() throws EmailException {
	new PlayBuilder().build();

	Email email = new SimpleEmail();
	email.setFrom("[email protected]");
	email.addTo("[email protected]");
	Mail.buildMessage(email);
}
 
Example 18
Source Project: nifi   File: GenerateAttachment.java    License: Apache License 2.0 5 votes vote down vote up
public MimeMessage SimpleEmailMimeMessage() {
    Email email = new SimpleEmail();
    try {
        email.setFrom(from);
        email.addTo(to);
        email.setSubject(subject);
        email.setMsg(message);
        email.setHostName(hostName);
        email.buildMimeMessage();
    } catch (EmailException e) {
        e.printStackTrace();
    }

    return email.getMimeMessage();
}
 
Example 19
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 LOG.addRecipientException(t, e);
      }
    }
  } else {
    throw LOG.missingRecipientsException();
  }
}
 
Example 20
Source Project: spring-boot   File: SendEmaiWithGmail.java    License: Apache License 2.0 4 votes vote down vote up
public void sendsimpleEmail2(Email email, String userName, String password,
		String subject, String simpleEmailBody, String from, String to,
		String cc, String bcc) throws EmailException {

	// 创建SimpleEmail对象

	// 显示调试信息用于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);

	// 设置邮件正文
	email.setMsg(simpleEmailBody);

	// 就是send发送
	email.send();

	// 这个是我自己写的。
	System.out.println("The SimpleEmail send sucessful!");

}