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

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

Introduction

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

Prototype

public void setHostName(final String aHostName) 

Source Link

Document

Set the hostname of the outgoing mail server.

Usage

From source file:org.polymap.rhei.um.email.EmailService.java

public void send(Email email) throws EmailException {
    String env = System.getProperty("org.polymap.rhei.um.SMTP");
    if (env == null) {
        throw new IllegalStateException(
                "Environment variable missing: org.polymap.rhei.um.SMTP. Format: <host>|<login>|<passwd>|<from>");
    }//from  w w  w  . j a  v  a  2 s .co  m
    String[] parts = StringUtils.split(env, "|");
    if (parts.length < 3 || parts.length > 4) {
        throw new IllegalStateException(
                "Environment variable wrong: org.polymap.rhei.um.SMTP. Format: <host>|<login>|<passwd>|<from> : "
                        + env);
    }

    email.setDebug(true);
    email.setHostName(parts[0]);
    //email.setSmtpPort( 465 );
    //email.setSSLOnConnect( true );
    email.setAuthenticator(new DefaultAuthenticator(parts[1], parts[2]));
    if (email.getFromAddress() == null && parts.length == 4) {
        email.setFrom(parts[3]);
    }
    if (email.getSubject() == null) {
        throw new EmailException("Missing subject.");
    }
    email.send();
}

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

public void testCommonsEmailOneWaySeparateSessions() {

    Queue emailQueue = null;// w  w w  .jav a2s  . c o  m
    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

/**
 * Apply server configuration to email./*from   ww  w. j a v a2s  .  c o  m*/
 */
@VisibleForTesting
Email apply(final EmailConfiguration configuration, final Email mail) throws EmailException {
    mail.setHostName(configuration.getHost());
    mail.setSmtpPort(configuration.getPort());
    mail.setAuthentication(configuration.getUsername(), configuration.getPassword());

    mail.setStartTLSEnabled(configuration.isStartTlsEnabled());
    mail.setStartTLSRequired(configuration.isStartTlsRequired());
    mail.setSSLOnConnect(configuration.isSslOnConnectEnabled());
    mail.setSSLCheckServerIdentity(configuration.isSslCheckServerIdentityEnabled());
    mail.setSslSmtpPort(Integer.toString(configuration.getPort()));

    // default from address
    if (mail.getFromAddress() == null) {
        mail.setFrom(configuration.getFromAddress());
    }

    // apply subject prefix if configured
    String subjectPrefix = configuration.getSubjectPrefix();
    if (subjectPrefix != null) {
        String subject = mail.getSubject();
        mail.setSubject(String.format("%s %s", subjectPrefix, subject));
    }

    // do this last (mail properties are set up from the email fields when you get the mail session)
    if (configuration.isNexusTrustStoreEnabled()) {
        SSLContext context = trustStore.getSSLContext();
        Session session = mail.getMailSession();
        Properties properties = session.getProperties();
        properties.remove(EmailConstants.MAIL_SMTP_SOCKET_FACTORY_CLASS);
        properties.put(EmailConstants.MAIL_SMTP_SSL_ENABLE, true);
        properties.put("mail.smtp.ssl.socketFactory", context.getSocketFactory());
    }

    return mail;
}

From source file:org.structr.common.MailHelper.java

private static void setup(final Email mail, final String to, final String toName, final String from,
        final String fromName, final String cc, final String bcc, final String bounce, final String subject)
        throws EmailException {

    // FIXME: this might be slow if the config file is read each time
    final Properties config = Services.getInstance().getCurrentConfig();
    final String smtpHost = config.getProperty(Services.SMTP_HOST, "localhost");
    final String smtpPort = config.getProperty(Services.SMTP_PORT, "25");
    final String smtpUser = config.getProperty(Services.SMTP_USER);
    final String smtpPassword = config.getProperty(Services.SMTP_PASSWORD);
    final String smtpUseTLS = config.getProperty(Services.SMTP_USE_TLS, "true");
    final String smtpRequireTLS = config.getProperty(Services.SMTP_REQUIRE_TLS, "false");

    mail.setCharset(charset);//from w w w . j  a  va2  s .  c om
    mail.setHostName(smtpHost);
    mail.setSmtpPort(Integer.parseInt(smtpPort));
    mail.setStartTLSEnabled(Boolean.parseBoolean(smtpUseTLS));
    mail.setStartTLSRequired(Boolean.parseBoolean(smtpRequireTLS));
    mail.setCharset(charset);
    mail.setHostName(smtpHost);
    mail.setSmtpPort(Integer.parseInt(smtpPort));

    if (StringUtils.isNotBlank(smtpUser) && StringUtils.isNotBlank(smtpPassword)) {
        mail.setAuthentication(smtpUser, smtpPassword);
    }

    mail.addTo(to, toName);
    mail.setFrom(from, fromName);

    if (StringUtils.isNotBlank(cc)) {
        mail.addCc(cc);
    }

    if (StringUtils.isNotBlank(bcc)) {
        mail.addBcc(bcc);
    }

    if (StringUtils.isNotBlank(bounce)) {
        mail.setBounceAddress(bounce);
    }

    mail.setSubject(subject);

}

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 {// www .j av  a  2 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.xerela.server.birt.ReportJob.java

private void setupEmail(JobExecutionContext executionContext, String emailTo, String emailCc, Email email)
        throws AddressException, EmailException {
    InternetAddress[] toAddrs = InternetAddress.parse(emailTo);
    email.setTo(Arrays.asList(toAddrs));

    if (emailCc != null && emailCc.trim().length() > 0) {
        InternetAddress[] ccAddrs = InternetAddress.parse(emailCc);
        email.setCc(Arrays.asList(ccAddrs));
    }//from   w w  w  .j  a  va  2s .co  m

    email.setCharset("utf-8"); //$NON-NLS-1$
    email.setHostName(System.getProperty(MAIL_HOST_PROP, "mail")); //$NON-NLS-1$
    String authUser = System.getProperty(MAIL_AUTH_USER_PROP);
    if (authUser != null) {
        email.setAuthentication(authUser, System.getProperty(MAIL_AUTH_PASSWORD_PROP));
    }
    email.setFrom(System.getProperty(MAIL_FROM_PROP), System.getProperty(MAIL_FROM_NAME_PROP));
    email.setSubject(
            Messages.bind(Messages.ReportJob_emailSubject, executionContext.getJobDetail().getFullName()));
    email.addHeader("X-Mailer", "Xerela Mailer"); //$NON-NLS-1$ //$NON-NLS-2$
    email.setDebug(Boolean.getBoolean("org.xerela.mail.debug")); //$NON-NLS-1$
}

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

/**
 * Sends an email or text notification upon successful access.
 * @param requester/*from w  w w.  ja  va  2 s  . c om*/
 * @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   w  w w .j  a va  2 s.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);// ww w.j a v a 2 s  .co 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.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 .  ja v  a  2s . c  o 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;
}