Example usage for org.apache.commons.mail Email send

List of usage examples for org.apache.commons.mail Email send

Introduction

In this page you can find the example usage for org.apache.commons.mail Email send.

Prototype

public String send() throws EmailException 

Source Link

Document

Sends the email.

Usage

From source file:com.intuit.wasabi.email.impl.EmailServiceImpl.java

void send(String subject, String msg, String... to) {

    String[] clearTo = removeInvalidEmails(to);

    if (isActive()) {
        try {//from  w w w.  j  a v a2s. c o  m
            Email email = createSimpleMailService();
            email.setHostName(host);
            email.setFrom(from);
            email.setSubject(subjectPrefix + " " + subject);
            email.setMsg(msg);
            email.addTo(clearTo);
            email.send();
        } catch (EmailException mailExcp) {
            LOGGER.error("Email could not be send because of " + mailExcp.getMessage());
            throw new WasabiEmailException("Email: " + emailToString(subject, msg, to) + " could not be sent.",
                    mailExcp);
        }
    } else {
        //if the service is not active log the email that would have been send and throw error
        LOGGER.info("EmailService would have sent: " + emailToString(subject, msg, to));
        throw new WasabiEmailException(ErrorCode.EMAIL_NOT_ACTIVE_ERROR, "The EmailService is not active.");
    }
}

From source file:br.com.recursive.biblioteca.servicos.EmailService.java

public void sendHtmlEmail(Pessoa pessoa) throws EmailException {

    Email email = new HtmlEmail();
    email.setAuthenticator(new DefaultAuthenticator("claupwd@gmail.com", "@claupwd2014"));
    email.setHostName("smtp.gmail.com");
    email.setFrom("claupwd@gmail.com");
    email.setSubject("SIB Online - Recuperao de Senha");
    email.setMsg(createMessage(pessoa));
    email.addTo(pessoa.getContato().getEmail());
    email.setSSL(true);//w w w .j av a 2  s. co  m
    //Se true, exibe na saida todo o processo do envio do email
    email.setDebug(true);
    email.send();
}

From source file:com.cognifide.qa.bb.email.EmailSender.java

public void sendEmail(final EmailData emailData) {
    try {/*from  ww w . jav  a2s . c  o m*/
        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);
    }
}

From source file:gobblin.util.EmailUtils.java

/**
 * A general method for sending emails.// ww w .java  2  s. c  o  m
 *
 * @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();
}

From source file:net.sasasin.sreader.batch.publish.GMailPublisher.java

@Override
public void publish(ContentViewId content) {
    try {/*from  w  w w.  ja  v  a2 s  . c  om*/
        Email email = new SimpleEmail();
        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(587);
        email.setStartTLSEnabled(true);
        email.setCharset("UTF-8");

        email.setAuthenticator(new DefaultAuthenticator(content.getEmail(), content.getPassword()));

        email.setFrom(content.getEmail());
        email.addTo(content.getEmail());
        email.setSubject(content.getTitle());
        email.setMsg(content.getUrl() + "\n" + content.getFullText());

        email.send();
        log(content);
    } catch (EmailException e) {
        e.printStackTrace();
    }
}

From source file:com.projetIF4.controller.MailControleur.java

public void mail() throws EmailException {
    Email email = new SimpleEmail();
    email.setCharset("UTF-8");
    email.setHostName("smtp.googlemail.com");
    email.setSmtpPort(465);/*from ww w .  j a v  a2 s.  c o  m*/
    email.setAuthenticator(new DefaultAuthenticator("fst.rnu.info@gmail.com", "adminFST123456789"));
    email.setSSLOnConnect(true);
    email.setFrom("fst.rnu.info@gmail.com", "Dpartement Informatique FST");
    email.setSubject(objet);
    email.setMsg(message);
    email.addTo(mailDestination);
    email.send();
}

From source file:beanView.MbVListaEmail.java

public void sendMail() {
    String subject = nombre + " " + eMail;
    try {/*from w  ww .  j a  va2  s  .c  o  m*/

        Email email = new SimpleEmail();
        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("altabar.listas", "Nivde017"));
        email.setSSLOnConnect(true);
        email.isStartTLSEnabled();
        email.setFrom("altabar.listas@gmail.com");
        email.setSubject(subject);
        email.setMsg(message);
        email.addTo("eacunagon@gmail.com");
        email.send();
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_INFO, "Listo!", "Lista enviada"));
    } catch (Exception ex) {
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", ex.getMessage()));
        eMail = "";
        nombre = "";
        message = "";

    }

}

From source file:com.turn.sorcerer.util.email.Emailer.java

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);/*from ww w. jav a 2 s . c o m*/
    }
    email.setFrom(
            SorcererInjector.get().getModule().getName() + "@" + InetAddress.getLocalHost().getHostName());
    email.setSubject(title);
    email.setMsg(body);
    email.send();

}

From source file:br.com.verificanf.bo.NotaBO.java

public void buscar() {
    /*Inicio - Pegar Configuraes de email do arquivo*/
    try {// w w w .  j  a  v a 2s .co  m
        String local = new File("./email.txt").getCanonicalFile().toString();
        File arq = new File(local);
        boolean existe = arq.exists();
        if (existe) {
            FileReader fr = new FileReader(arq);
            BufferedReader br = new BufferedReader(fr);
            while (br.ready()) {
                String linha = br.readLine();
                if (linha.contains("host:")) {
                    hostEmail = linha.replace("host:", "").replace(" ", "");
                }
                if (linha.contains("port:")) {
                    portEmail = linha.replace("port:", "").replace(" ", "");
                }
                if (linha.contains("user:")) {
                    userEmail = linha.replace("user:", "").replace(" ", "");
                }
                if (linha.contains("pass:")) {
                    passEmail = linha.replace("pass:", "").replace(" ", "");
                }
                if (linha.contains("from:")) {
                    fromEmail = linha.replace("from:", "").replace(" ", "");
                }
                if (linha.contains("to:")) {
                    toEmail = linha.replace("to:", "").replace(" ", "");
                }
            }

        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(NotaBO.class.getName()).log(Level.SEVERE, null, ex);
        StackTraceElement st[] = ex.getStackTrace();
        String erro = "";
        for (int i = 0; i < st.length; i++) {
            erro += st[i].toString() + "\n";
        }

    } catch (IOException ex) {
        Logger.getLogger(NotaBO.class.getName()).log(Level.SEVERE, null, ex);
        StackTraceElement st[] = ex.getStackTrace();
        String erro2 = "";
        for (int i = 0; i < st.length; i++) {
            erro2 += st[i].toString() + "\n";
        }

    }
    /*FIM - Pegar Configuraes de email do arquivo*/

    NotaDAO notaDAO = new NotaDAO();
    try {
        ultimasAtual = notaDAO.getUltimaNotaMesAtual();
        ultimasAnterior = notaDAO.getUltimaNotaMesAnterior();
        naoEncontradas = new ArrayList<>();
        for (Nota notaAnterior : ultimasAnterior) {

            for (Nota notaAtual : ultimasAtual) {

                if (notaAnterior.getLoja() == notaAtual.getLoja()) {
                    //System.out.println("Anterior Loja: "+notaAnterior.getLoja()+" Nota: "+notaAnterior.getNumero());
                    //System.out.println("Atual Loja: "+notaAtual.getLoja()+" Nota: "+notaAtual.getNumero());
                    Integer numero = 0;
                    for (Integer i = notaAnterior.getNumero(); i <= notaAtual.getNumero(); i++) {
                        numero = i;
                        Nota notacorrente = new Nota();
                        notacorrente.setLoja(notaAnterior.getLoja());
                        notacorrente.setNumero(numero);
                        notacorrente.setSerie(notaAnterior.getSerie());

                        //System.out.println("Corrente Loja: "+notacorrente.getLoja()+" Nota: "+notacorrente.getNumero());
                        if (!notaDAO.notaIsValida(notacorrente)) {
                            System.out.println("Loja " + notaAnterior.getLoja() + " Numero: " + numero);
                            naoEncontradas.add(notacorrente);
                            msg = msg.concat("      Loja: " + notacorrente.getLoja() + " Nota: "
                                    + notacorrente.getNumero() + " Serie: " + notacorrente.getSerie() + " \n");
                        }

                    }
                }
            }
        }
        if (naoEncontradas.size() > 0) {
            Email email = new SimpleEmail();
            email.setHostName(hostEmail);
            email.setSmtpPort(Integer.parseInt(portEmail));
            email.setAuthentication(userEmail, passEmail);
            email.setFrom(fromEmail);
            email.setSubject("Alerta Nerus!!");
            email.setMsg(msg);

            email.addTo(toEmail);
            email.send();
        }
    } catch (Exception ex) {
        Logger.getLogger(NotaBO.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.github.triceo.robozonky.notifications.email.AbstractEmailingListener.java

@Override
public void handle(final T event) {
    if (!this.shouldSendEmail(event)) {
        LOGGER.debug("Will not send e-mail.");
        return;/*from  w w  w .j  av a 2 s .  com*/
    } else
        try {
            final Email email = AbstractEmailingListener.createNewEmail(properties);
            email.setSubject(this.getSubject(event));
            email.setMsg(TemplateProcessor.INSTANCE.process(this.getTemplateFileName(), this.getData(event)));
            LOGGER.debug("Will send '{}' from {} to {} through {}:{} as {}.", email.getSubject(),
                    email.getFromAddress(), email.getToAddresses(), email.getHostName(), email.getSmtpPort(),
                    properties.getSmtpUsername());
            email.send();
            emailsOfThisType.increase();
            this.properties.getGlobalCounter().increase();
        } catch (final Exception ex) {
            throw new RuntimeException("Failed processing event.", ex);
        }

}