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:org.sonatype.nexus.internal.email.EmailManagerImpl.java

@Override
public void send(final Email mail) throws EmailException {
    checkNotNull(mail);/*from   w  ww . jav  a2s.c o  m*/

    EmailConfiguration model = getConfigurationInternal();
    if (model.isEnabled()) {
        Email prepared = apply(model, mail);
        prepared.send();
    }
}

From source file:org.sonatype.nexus.internal.email.EmailManagerImpl.java

@Override
public void sendVerification(final EmailConfiguration configuration, final String address)
        throws EmailException {
    checkNotNull(configuration);/*from w w w  . j a va2s  . c  o m*/
    checkNotNull(address);

    Email mail = new SimpleEmail();
    mail.setSubject("Email configuration verification");
    mail.addTo(address);
    mail.setMsg("Verification successful");
    mail = apply(configuration, mail);
    mail.send();
}

From source file:org.thousandturtles.gmail_demo.Main.java

public static void main(String[] args) {
    MailInfoRetriever retriever = new CLIMailInfoRetriever();
    MailInfo mailInfo = retriever.retrieveMailInfo();

    if (mailInfo.isNoAuth()) {
        System.out.println("Using No auth, mail with aspmx.l.google.com");
    } else {/*  w  w  w .j  a  v a 2 s . c o  m*/
        System.out.printf("Username: %s%n", mailInfo.getUsername());
        System.out.printf("Password: %c***%c%n", mailInfo.getPassword().charAt(0),
                mailInfo.getPassword().charAt(mailInfo.getPassword().length() - 1));
    }
    System.out.printf("Mail target: %s%n", mailInfo.getMailTo());

    try {
        Email mail = new SimpleEmail();
        if (mailInfo.isNoAuth()) {
            mail.setHostName("aspmx.l.google.com");
            mail.setSmtpPort(25);
            mail.setFrom("no-reply@thousandturtles.org");
        } else {
            mail.setHostName("smtp.gmail.com");
            mail.setSmtpPort(465);
            mail.setAuthentication(mailInfo.getUsername(), mailInfo.getPassword());
            mail.setSSLOnConnect(true);
            mail.setFrom(mailInfo.getMailer());
        }
        mail.setCharset("UTF-8");
        mail.addTo(mailInfo.getMailTo(), "White Mouse");
        mail.setSubject("");
        mail.setMsg("?\nThis is a test mail!\n");
        mail.send();

        System.out.println("Mail sent successfully.");
    } catch (EmailException ee) {
        ee.printStackTrace();
    }
}

From source file:org.vas.mail.MailWorker.java

void send(Mail mail) {
    if (logger.isTraceEnabled()) {
        logger.trace("New mail to send - {}", mail.subject);
    }/*from ww  w  .  j a v a 2  s. co  m*/

    Email email = smtp.emptyEmail();
    email.setSubject(mail.subject);
    try {
        email.setFrom(mail.from);
        email.setTo(Arrays.asList(new InternetAddress(mail.to)));
        email.setMsg(mail.body);

        if (logger.isDebugEnabled()) {
            logger.debug("Send mail {}", mail.subject);
        }

        email.send();
    } catch (EmailException | AddressException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.xerela.server.birt.ReportJob.java

/**
 * Email the report if the JobData defines the required parameters,
 * otherwise this method just returns without doing anything.
 *
 * @param intermediate the BIRT intermediate format file
 * @param executionContext the Quartz JobExecutionContext of this job
 *///from   w ww .  ja va 2  s  .  c  o m
@SuppressWarnings("nls")
private void emailReport(File intermediate, JobExecutionContext executionContext) {
    JobDataMap jobData = executionContext.getMergedJobDataMap();
    boolean emailAttachment = jobData.containsKey(REPORT_EMAIL_ATTACHMENT)
            ? jobData.getBooleanValue(REPORT_EMAIL_ATTACHMENT)
            : false;
    boolean emailLink = jobData.containsKey(REPORT_EMAIL_LINK) ? jobData.getBooleanValue(REPORT_EMAIL_LINK)
            : false;
    String emailTo = jobData.getString(REPORT_EMAIL_TO);
    String emailCc = jobData.getString(REPORT_EMAIL_CC);
    String reportFormat = jobData.getString(REPORT_EMAIL_FORMAT);

    if (!validateEmailProperties(emailAttachment, emailLink, emailTo, reportFormat)) {
        return;
    }

    try {
        Email email = null;
        if (reportFormat.equals("pdf")) {
            email = new MultiPartEmail();
        } else if (reportFormat.equals("html")) {
            email = new HtmlEmail();
        }

        setupEmail(executionContext, emailTo, emailCc, email);

        // Create the attachment
        if (emailAttachment) {
            final File render = RenderElf.render(intermediate, executionData.getId(), reportFormat);

            if (reportFormat.equals("pdf")) {
                EmailAttachment attachment = new EmailAttachment();
                attachment.setPath(render.getAbsolutePath());
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setDescription(reportTitle);
                attachment.setName(String.format("%s.%s", reportTitle, reportFormat)); //$NON-NLS-1$
                ((MultiPartEmail) email).attach(attachment);
            } else if (reportFormat.equals("html")) {
                HtmlEmail htmlEmail = (HtmlEmail) email;
                String html = stringFromFile(render);

                final String pathStub = render.getName().replaceFirst("\\.[a-z]+$", ""); //$NON-NLS-1$ //$NON-NLS-2$
                File parentDir = new File(render.getParent());
                File[] listFiles = parentDir.listFiles(new FileFilter() {
                    public boolean accept(File pathname) {
                        return pathname.getName().startsWith(pathStub) && !pathname.getName().endsWith("html"); //$NON-NLS-1$
                    }
                });

                for (File image : listFiles) {
                    String cid = htmlEmail.embed(image);
                    String regex = "src=.+" + image.getName();
                    html = html.replaceAll(regex, "src=\"cid:" + cid);
                }

                htmlEmail.setHtmlMsg(html);
            }
        }

        if (emailLink) {
        }

        email.send();
    } catch (AddressException ae) {
        LOGGER.error(Messages.bind(Messages.ReportJob_badAddresses, reportTitle), ae);
    } catch (EmailException ee) {
        LOGGER.error(Messages.bind(Messages.ReportJob_errorSending, reportTitle), ee);
    } catch (EngineException ee) {
        LOGGER.error(Messages.bind(Messages.ReportJob_errorSending, reportTitle), ee);
    } catch (IOException ie) {
        LOGGER.error(Messages.bind(Messages.ReportJob_errorSending, reportTitle), ie);
    }
}

From source file:org.ygl.plexc.PlexcLibrary.java

/**
 * Sends an email or text notification upon successful access.
 * @param requester/*from  w ww .  ja  v a  2  s. com*/
 * @return
 */
public boolean notify_1(Term requester) {
    final String user = getCurrentUser();
    final String host = "localhost";
    final String subject = "PlexC access notification";
    final String text = String.format("%s, %s has been granted access to your location.", user,
            requester.getTerm().toString());

    Email email = new SimpleEmail();
    email.setSubject(subject);
    email.setHostName(host);
    email.setSmtpPort(465);

    try {
        email.setFrom("noreply@plexc.com");
        email.setMsg(text);
        email.addTo(user);
        email.send();
    } catch (EmailException e) {
        LOG.warn(e.getMessage());
        return false;
    }
    return true;
}

From source file:paquetes.AlertSchedule.java

@Schedule(hour = "8", dayOfWeek = "*", info = "Todos los dias a las 8:00 a.m.")
//@Schedule(second = "*", minute = "*/10", hour = "*", persistent= true, info = "cada 10 minutos")

public void performTask() throws EmailException {

    long timeInit = System.currentTimeMillis();
    ConfiguracionMail();/*from   www  .  j  av a2s .c  om*/

    log.info(":. Inicio TareaProgramada cada dia");

    try {
        timeInit = System.currentTimeMillis();

        obtenerAlertas();

        // Luego de obtener las alertas las recorremos para conformar cada uno de los selects de validacion
        alertas.stream().forEach((ale) -> {

            id_ale = ale.getId_ale();
            llenarAlertasUsuarios(ale.getId_ale());
            verificarPorTipoAlerta(ale);
            nom_tip_ale = ale.getNom_tip_ale();

            logale.stream().forEach((lgal) -> {

                try {
                    Email email = new SimpleEmail();
                    email.setHostName(this.hostname);
                    email.setSmtpPort(Integer.parseInt(this.smtp_port));
                    email.setAuthenticator(new DefaultAuthenticator(this.user, this.pass));
                    // TLS agregado para server AWS Se quita comentario a setSSL.
                    email.setStartTLSEnabled(true);
                    email.setStartTLSRequired(true);

                    // Comentariado para funcionar con Gmail
                    //email.setSSLOnConnect(true);

                    email.setFrom(this.remitente);
                    email.setSubject(nom_tip_ale);
                    email.setMsg(lgal.getAle_des());

                    alertasusuarios.stream().forEach((mailDestino) -> {
                        try {
                            email.addTo(mailDestino.getMailusu());
                        } catch (Exception e) {
                            System.out.println("Error en la obtencion de destinatarios. " + e.getMessage());
                        }
                    });

                    email.send();
                } catch (Exception e) {
                    System.out.println("Error en la conformacion del correo. " + e.getMessage());
                }
            });
        });
    } catch (Exception e) {
        log.error("Error en la tarea programada");
        log.info(e);
    }

    long time = System.currentTimeMillis();
    time = System.currentTimeMillis() - timeInit;
    log.info(":. Fin tarea programada. Tiempo de proceso = " + time);

}

From source file:rapternet.irc.bots.wheatley.listeners.AutodlText.java

@Override
public void onMessage(final MessageEvent event) throws Exception {
    String message = Colors.removeFormattingAndColors(event.getMessage());
    if (event.getUser().getNick().equals("SHODAN")) { //Auto Download bot nick
        if (message.startsWith("Saved")) {
            // LOAD XML
            File fXmlFile = new File("Settings.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            NodeList nList = doc.getElementsByTagName("email");
            int mailsetting = 0; //NOTE: can setup multiple email profiles for different functions here
            Node nNode = nList.item(mailsetting);
            Element eElement = (Element) nNode;
            //SEND EMAIL STUFF
            Email email = new SimpleEmail();
            email.setHostName(eElement.getElementsByTagName("hostname").item(0).getTextContent());
            email.setSmtpPort(465);//from w w w .  ja v a2s.  c o  m
            email.setAuthenticator(
                    new DefaultAuthenticator(eElement.getElementsByTagName("username").item(0).getTextContent(),
                            eElement.getElementsByTagName("password").item(0).getTextContent()));
            email.setSSLOnConnect(true);
            email.setFrom(eElement.getElementsByTagName("from").item(0).getTextContent());
            email.setSubject(eElement.getElementsByTagName("subject").item(0).getTextContent());
            email.setMsg(message);
            email.addTo(eElement.getElementsByTagName("to").item(0).getTextContent());
            email.send();
            event.getBot().sendIRC().message(event.getChannel().getName(),
                    "AAAaaaAAHhhH I just connected to an email server, I feel dirty");
        }
    }
}

From source file:ru.codeinside.adm.CheckExecutionThread.java

@Override
public void run() {
    try {//from  w ww .  java 2 s.com
        Email email = checkExecutionDates.checkDates(processEngine);
        if (email != null) {
            email.send();
        }
    } catch (EmailException e) {
        checkExecutionDates.createLog(e);
    }
}

From source file:ru.codeinside.adm.ui.AdminApp.java

private Panel createEmailDatesPanel() {
    VerticalLayout emailDates = new VerticalLayout();
    emailDates.setSpacing(true);/*ww w  .  ja  v  a  2 s.c  o m*/
    emailDates.setMargin(true);
    emailDates.setSizeFull();
    Panel panel2 = new Panel(" ? ??", emailDates);
    panel2.setSizeFull();

    final TextField emailToField = new TextField("e-mail ?:");
    emailToField.setValue(get(API.EMAIL_TO));
    emailToField.setRequired(true);
    emailToField.setReadOnly(true);
    emailToField.addValidator(new EmailValidator("  e-mail ?"));

    final TextField receiverNameField = new TextField("? ?:");
    receiverNameField.setValue(get(API.RECEIVER_NAME));
    receiverNameField.setRequired(true);
    receiverNameField.setReadOnly(true);

    final TextField emailFromField = new TextField("e-mail ?:");
    emailFromField.setValue(get(API.EMAIL_FROM));
    emailFromField.setRequired(true);
    emailFromField.setReadOnly(true);
    emailFromField.addValidator(new EmailValidator("  e-mail ?"));

    final TextField senderLoginField = new TextField(" ?:");
    senderLoginField.setValue(get(API.SENDER_LOGIN));
    senderLoginField.setRequired(true);
    senderLoginField.setReadOnly(true);

    final TextField senderNameField = new TextField("? ?:");
    senderNameField.setValue(get(API.SENDER_NAME));
    senderNameField.setRequired(true);
    senderNameField.setReadOnly(true);

    final PasswordField passwordField = new PasswordField(":");
    passwordField.setValue(API.PASSWORD);
    passwordField.setRequired(true);
    passwordField.setReadOnly(true);

    final TextField hostField = new TextField("SMTP ?:");
    String host = get(API.HOST);
    hostField.setValue(host == null ? "" : host);
    hostField.setRequired(true);
    hostField.setReadOnly(true);

    final TextField portField = new TextField(":");
    String port = get(API.PORT);
    portField.setValue(port == null ? "" : port);
    portField.setRequired(true);
    portField.setReadOnly(true);
    portField.addValidator(new IntegerValidator(" "));

    final CheckBox tls = new CheckBox("? TLS",
            AdminServiceProvider.getBoolProperty(API.TLS));
    tls.setReadOnly(true);

    final Button save = new Button("");
    save.setVisible(false);
    final Button cancel = new Button("");
    cancel.setVisible(false);
    final Button change = new Button("");
    final Button check = new Button("");
    check.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            String emailTo = get(API.EMAIL_TO);
            String receiverName = get(API.RECEIVER_NAME);
            String hostName = get(API.HOST);
            String port = get(API.PORT);
            String senderLogin = get(API.SENDER_LOGIN);
            String password = get(API.PASSWORD);
            String emailFrom = get(API.EMAIL_FROM);
            String senderName = get(API.SENDER_NAME);
            if (emailTo.isEmpty() || receiverName.isEmpty() || hostName.isEmpty() || port.isEmpty()
                    || senderLogin.isEmpty() || password.isEmpty() || emailFrom.isEmpty()
                    || senderName.isEmpty()) {
                check.getWindow().showNotification("? ? ");
                return;
            }
            Email email = new SimpleEmail();
            try {
                email.setSubject("? ?");
                email.setMsg("? ?");
                email.addTo(emailTo, receiverName);
                email.setHostName(hostName);
                email.setSmtpPort(Integer.parseInt(port));
                email.setTLS(AdminServiceProvider.getBoolProperty(API.TLS));
                email.setAuthentication(senderLogin, password);
                email.setFrom(emailFrom, senderName);
                email.setCharset("utf-8");
                email.send();
            } catch (EmailException e) {
                check.getWindow().showNotification(e.getMessage());
                return;
            }
            check.getWindow().showNotification("? ? ");
        }
    });
    change.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            emailToField.setReadOnly(false);
            receiverNameField.setReadOnly(false);
            emailFromField.setReadOnly(false);
            senderLoginField.setReadOnly(false);
            senderNameField.setReadOnly(false);
            passwordField.setReadOnly(false);
            hostField.setReadOnly(false);
            portField.setReadOnly(false);
            tls.setReadOnly(false);

            change.setVisible(false);
            check.setVisible(false);
            save.setVisible(true);
            cancel.setVisible(true);
        }
    });
    save.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            if (StringUtils.isEmpty((String) emailToField.getValue())
                    || StringUtils.isEmpty((String) receiverNameField.getValue())
                    || StringUtils.isEmpty((String) emailFromField.getValue())
                    || StringUtils.isEmpty((String) senderNameField.getValue())
                    || StringUtils.isEmpty((String) senderLoginField.getValue())
                    || StringUtils.isEmpty((String) passwordField.getValue())
                    || StringUtils.isEmpty((String) hostField.getValue()) || portField.getValue() == null) {
                emailToField.getWindow().showNotification(" ?",
                        Window.Notification.TYPE_HUMANIZED_MESSAGE);
                return;
            }
            boolean errors = false;
            try {
                emailToField.validate();
            } catch (Validator.InvalidValueException ignore) {
                errors = true;
            }
            try {
                emailFromField.validate();
            } catch (Validator.InvalidValueException ignore) {
                errors = true;
            }
            try {
                portField.validate();
            } catch (Validator.InvalidValueException ignore) {
                errors = true;
            }
            if (errors) {
                return;
            }
            set(API.EMAIL_TO, emailToField.getValue());
            set(API.RECEIVER_NAME, receiverNameField.getValue());
            set(API.EMAIL_FROM, emailFromField.getValue());
            set(API.SENDER_LOGIN, senderLoginField.getValue());
            set(API.SENDER_NAME, senderNameField.getValue());
            set(API.PASSWORD, passwordField.getValue());
            set(API.HOST, hostField.getValue());
            set(API.PORT, portField.getValue());
            set(API.TLS, tls.getValue());

            emailToField.setReadOnly(true);
            receiverNameField.setReadOnly(true);
            emailFromField.setReadOnly(true);
            senderLoginField.setReadOnly(true);
            senderNameField.setReadOnly(true);
            passwordField.setReadOnly(true);
            hostField.setReadOnly(true);
            portField.setReadOnly(true);
            tls.setReadOnly(true);

            save.setVisible(false);
            cancel.setVisible(false);
            change.setVisible(true);
            check.setVisible(true);
            emailToField.getWindow().showNotification("?? ?",
                    Window.Notification.TYPE_HUMANIZED_MESSAGE);
        }
    });
    cancel.addListener(new Button.ClickListener() {
        @Override
        public void buttonClick(Button.ClickEvent event) {
            emailToField.setValue(get(API.EMAIL_TO));
            receiverNameField.setValue(get(API.RECEIVER_NAME));
            emailFromField.setValue(get(API.EMAIL_FROM));
            senderLoginField.setValue(get(API.SENDER_LOGIN));
            senderNameField.setValue(get(API.SENDER_NAME));
            passwordField.setValue(get(API.PASSWORD));
            hostField.setValue(get(API.HOST));
            portField.setValue(get(API.PORT));
            tls.setValue(AdminServiceProvider.getBoolProperty(API.TLS));

            emailToField.setReadOnly(true);
            receiverNameField.setReadOnly(true);
            emailFromField.setReadOnly(true);
            senderLoginField.setReadOnly(true);
            senderNameField.setReadOnly(true);
            passwordField.setReadOnly(true);
            hostField.setReadOnly(true);
            portField.setReadOnly(true);
            tls.setReadOnly(true);

            save.setVisible(false);
            cancel.setVisible(false);
            change.setVisible(true);
            check.setVisible(true);
        }
    });

    FormLayout fields1 = new FormLayout();
    fields1.setSizeFull();
    fields1.addComponent(senderLoginField);
    fields1.addComponent(passwordField);
    fields1.addComponent(hostField);
    fields1.addComponent(portField);
    fields1.addComponent(tls);

    FormLayout fields2 = new FormLayout();
    fields2.setSizeFull();
    fields2.addComponent(emailToField);
    fields2.addComponent(receiverNameField);
    fields2.addComponent(emailFromField);
    fields2.addComponent(senderNameField);

    HorizontalLayout fields = new HorizontalLayout();
    fields.setSpacing(true);
    fields.setSizeFull();
    fields.addComponent(fields1);
    fields.addComponent(fields2);

    HorizontalLayout buttons = new HorizontalLayout();
    buttons.setSpacing(true);
    buttons.addComponent(change);
    buttons.addComponent(save);
    buttons.addComponent(cancel);
    buttons.addComponent(check);

    Label label = new Label("?? ");
    label.addStyleName(Reindeer.LABEL_H2);
    emailDates.addComponent(label);
    emailDates.addComponent(fields);
    emailDates.addComponent(buttons);
    emailDates.setExpandRatio(fields, 1f);
    return panel2;
}