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

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

Introduction

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

Prototype

public abstract Email setMsg(String msg) throws EmailException;

Source Link

Document

Define the content of the mail.

Usage

From source file:org.pepstock.jem.notify.engine.EmailNotifier.java

/**
 * This method sends an <code>Email</code>. <br>
 * It sets in the parameter <code>Email</code> the properties of the
 * parameter <code>JemEmail</code>: From User Email Address, From User Name,
 * subject, text, email destination addresses. <br>
 * It sets in the parameter <code>Email</code> the Email Server property and
 * the optional <code>SMTP</code> port, the properties that indicates if it
 * must use <code>SSL</code> and <code>TLS</code> protocol, the useirid and
 * password for <code>SMTP</code> server authentication if needed, the
 * optional bounce address, the subject, the text, and the recipients of the
 * email./*from  www.j a  v  a  2 s . com*/
 * 
 * @param email the <code>JemEmail</code> with the properties of the email
 *            to be sent.
 * @param sendingEmail the real <code>Email</code> that will be sent.
 * @see JemEmail
 * @see Email
 * @throws SendMailException if an error occurs.
 */
private void sendEmail(JemEmail email, Email sendingEmail) throws SendMailException {
    try {
        sendingEmail.setHostName(this.emailServer);
        if (this.smtpPort != NO_SMTP_PORT) {
            sendingEmail.setSmtpPort(this.smtpPort);
        }
        sendingEmail.setFrom(email.getFromUserEmailAddress(), email.getFromUserName());
        if (email.hasSubject()) {
            sendingEmail.setSubject(email.getSubject());
        } else {
            // log no subject
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Subject");
        }
        if (email.hasText()) {
            sendingEmail.setMsg(email.getText());
        } else {
            // log no text message
            LogAppl.getInstance().emit(NotifyMessage.JEMN014W, "Text Message");
        }
        sendingEmail.setTo(email.getAllToEmailAddresses());
        if (null != this.bounceAddress) {
            sendingEmail.setBounceAddress(this.bounceAddress);
        }
        sendingEmail.setSentDate(new Date());
        sendingEmail.setSSL(this.isSSL);
        sendingEmail.setTLS(this.isTLS);
        if (null != this.authenticationUserId && null != this.authenticationPassword) {
            sendingEmail.setAuthenticator(
                    new DefaultAuthenticator(this.authenticationUserId, this.authenticationPassword));
        }
        sendingEmail.send();
        LogAppl.getInstance().emit(NotifyMessage.JEMN015I, email);
    } catch (EmailException eEx) {
        LogAppl.getInstance().emit(NotifyMessage.JEMN016E, eEx, email);
        throw new SendMailException(NotifyMessage.JEMN016E.toMessage().getFormattedMessage(email), eEx);
    }
}

From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

public void testCommonsEmailOneWaySeparateSessions() {

    Queue emailQueue = null;/*from  w w  w.  ja  va2s .com*/
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    Session clientSession = null;
    Session listenerSession = null;
    // it is not necessary to use the Email interface here
    // Email is used here just to allow for multiple types of emails to
    // occupy
    // the same varaible. SimpleEmail etc can each be used directly.
    List<Email> emails = new ArrayList<Email>();
    EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null,
            null, null, null);
    emails.add(new SimpleEmail(messagingService));
    emails.add(new MultiPartEmail(messagingService));
    emails.add(new HtmlEmail(messagingService));
    try {

        listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = listenerSession.createQueue(emailQueueName);

        consumer = listenerSession.createConsumer(emailQueue);

        consumer.setMessageListener(new EmailListener());

        listenerConn.start();

        listenerSession.run();

    } catch (JMSException e2) {
        e2.printStackTrace();
        Assert.assertTrue(false);
    }

    Wiser smtpServer = new Wiser();
    smtpServer.setPort(smtpTestPort);
    smtpServer.start();

    try {
        clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = clientSession.createQueue(emailQueueName);
        producer = clientSession.createProducer(emailQueue);

        clientConn.start();
        clientSession.run();

    } catch (JMSException e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }

    for (Email em : emails) {

        try {
            em.addTo(TEST_EMAIL_TO);
            em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL);
            // host and port will be ignored since the email session is
            // established
            // by
            // the listener
            em.setHostName("localhost");
            em.setSmtpPort(smtpTestPort);
            em.setSubject(TEST_EMAIL_SUBJECT);
            if (em instanceof HtmlEmail) {
                em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL);
            } else if (em instanceof MultiPartEmail) {
                em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL);
            } else if (em instanceof SimpleEmail) {
                em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL);
            }

        } catch (EmailException e1) {
            Assert.assertTrue(false);
            e1.printStackTrace();
        }

        try {
            em.buildMimeMessage();
        } catch (EmailException e1) {
            e1.printStackTrace();
            Assert.assertTrue(false);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {

            em.getMimeMessage().writeTo(os);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

        String content = os.toString();

        ObjectMessage om;
        try {
            om = clientSession.createObjectMessage(content);

            om.setJMSType(emailType);

            LOG.info("Client: Sending test message....");
            producer.send(om);
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

    }

    long start = System.currentTimeMillis();
    while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) {
        // wait for transport
    }
    Assert.assertTrue(listenerMessagesProcessed == 3);

    List<WiserMessage> messages = smtpServer.getMessages();
    Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3);

    for (WiserMessage wisermsg : messages) {
        String body = null;
        String subject = null;
        MimeMessage testmail = null;

        try {
            testmail = wisermsg.getMimeMessage();
        } catch (MessagingException e) {
            Assert.assertTrue(false);
            e.printStackTrace();
        }

        if (testmail != null) {
            LOG.info("SMTP server: test email received: ");
            try {
                LOG.info("To: " + testmail.getHeader("To", ","));

                LOG.info("Subject: " + testmail.getHeader("Subject", ","));
                body = getBodyAsString(testmail.getContent());
                subject = testmail.getHeader("Subject", ",");
            } catch (MessagingException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            } catch (IOException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            }
            LOG.info("Body: " + body);
            Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT));
            Assert.assertTrue(body.contains("This is a Commons"));
        } else {
            Assert.assertTrue(false);
        }
    }

    if (clientSession != null) {
        try {
            clientSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        clientSession = null;
    }

    if (listenerSession != null) {
        try {
            listenerSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        listenerSession = null;
    }

    smtpServer.stop();

}

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

@Override
public void sendVerification(final EmailConfiguration configuration, final String address)
        throws EmailException {
    checkNotNull(configuration);/*w  w w  . j  av  a2s  .c  om*/
    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.sonatype.nexus.internal.scheduling.NexusTaskFailureAlertEmailSender.java

private void sendEmail(final String address, final String taskId, final String taskName, final Throwable cause)
        throws Exception {
    Email mail = new SimpleEmail();
    mail.setSubject("Task execution failure");
    mail.addTo(address);//from   www .  j  a  v a2s  .com

    // FIXME: This should ideally render a user-configurable template
    StringWriter buff = new StringWriter();
    PrintWriter out = new PrintWriter(buff);
    if (taskId != null) {
        out.format("Task ID: %s%n", taskId);
    }
    if (taskName != null) {
        out.format("Task Name: %s%n", taskName);
    }
    if (cause != null) {
        out.println("Stack-trace:");
        cause.printStackTrace(out);
    }
    mail.setMsg(buff.toString());

    emailManager.get().send(mail);
}

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 {/*from   w ww  .  ja  va2 s .co 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 w ww.  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.ygl.plexc.PlexcLibrary.java

/**
 * Sends an email or text notification upon successful access.
 * @param requester//  w w  w . ja va  2 s.  co m
 * @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();/*w w w .  j  a  v  a 2 s. com*/

    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);/* www.  jav  a  2  s  .c  om*/
            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.CheckExecutionDates.java

@TransactionAttribute(REQUIRES_NEW)
public Email checkDates(ProcessEngine processEngine) throws EmailException {
    String emailTo = get(API.EMAIL_TO);
    String receiverName = get(API.RECEIVER_NAME);
    String hostName = get(API.HOST);
    String port = get(API.PORT);//from w  ww  .  j  a  v  a2s.  co m
    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()) {
        return null;
    }

    List<TaskDates> overdueTasks = new ArrayList<TaskDates>();
    List<Bid> overdueBids = new ArrayList<Bid>();
    List<TaskDates> endingTasks = new ArrayList<TaskDates>();
    List<Bid> endingBids = new ArrayList<Bid>();
    List<TaskDates> inactionTasks = new ArrayList<TaskDates>();

    Date currentDate = check(overdueTasks, overdueBids, endingTasks, endingBids, inactionTasks);

    Email email = new SimpleEmail();
    email.setSubject("[siu.oep-penza.ru]  ?? ?  ?  "
            + new SimpleDateFormat("yyyy.MM.dd HH:mm").format(currentDate));

    StringBuilder msg = new StringBuilder();
    msg.append(" !\n"
            + "  ?? ?  ? ?? ? [siu.oep-penza.ru]  ")
            .append(new SimpleDateFormat("yyyy.MM.dd").format(currentDate))
            .append(", ??  :\n\n");

    int n = 1;
    n = addTaskList(
            ",    ? ? ??",
            n, processEngine, overdueTasks, msg);
    n = addBidList(
            "?,    ? ? ??",
            n, overdueBids, msg);
    n = addTaskList(
            ", ? ??  ??  ?",
            n, processEngine, endingTasks, msg);
    n = addBidList(
            "?, ? ??  ??  ?",
            n, endingBids, msg);
    n = addTaskList(",  ???  ?:", n,
            processEngine, inactionTasks, msg);

    msg.append(
            "  ,  ? ? ?    !\n"
                    + " ?  ?  ? "
                    + "      . 8(8412)23-11-25 (. 45, 46, 47)");

    if (n == 1) {
        return null;
    }

    email.setMsg(msg.toString());
    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");

    return email;
}