Example usage for javax.mail Transport sendMessage

List of usage examples for javax.mail Transport sendMessage

Introduction

In this page you can find the example usage for javax.mail Transport sendMessage.

Prototype

public abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;

Source Link

Document

Send the Message to the specified list of addresses.

Usage

From source file:com.zimbra.cs.util.SmtpInject.java

public static void main(String[] args) {
    CliUtil.toolSetup();/*from w  w  w  . java2  s .  co m*/
    CommandLine cl = parseArgs(args);

    if (cl.hasOption("h")) {
        usage(null);
    }

    String file = null;
    if (!cl.hasOption("f")) {
        usage("no file specified");
    } else {
        file = cl.getOptionValue("f");
    }
    try {
        ByteUtil.getContent(new File(file));
    } catch (IOException ioe) {
        usage(ioe.getMessage());
    }

    String host = null;
    if (!cl.hasOption("a")) {
        usage("no smtp server specified");
    } else {
        host = cl.getOptionValue("a");
    }

    String sender = null;
    if (!cl.hasOption("s")) {
        usage("no sender specified");
    } else {
        sender = cl.getOptionValue("s");
    }

    String recipient = null;
    if (!cl.hasOption("r")) {
        usage("no recipient specified");
    } else {
        recipient = cl.getOptionValue("r");
    }

    boolean trace = false;
    if (cl.hasOption("T")) {
        trace = true;
    }

    boolean tls = false;
    if (cl.hasOption("t")) {
        tls = true;
    }

    boolean auth = false;
    String user = null;
    String password = null;
    if (cl.hasOption("A")) {
        auth = true;
        if (!cl.hasOption("u")) {
            usage("auth enabled, no user specified");
        } else {
            user = cl.getOptionValue("u");
        }
        if (!cl.hasOption("p")) {
            usage("auth enabled, no password specified");
        } else {
            password = cl.getOptionValue("p");
        }
    }

    if (cl.hasOption("v")) {
        mLog.info("SMTP server: " + host);
        mLog.info("Sender: " + sender);
        mLog.info("Recipient: " + recipient);
        mLog.info("File: " + file);
        mLog.info("TLS: " + tls);
        mLog.info("Auth: " + auth);
        if (auth) {
            mLog.info("User: " + user);
            char[] dummyPassword = new char[password.length()];
            Arrays.fill(dummyPassword, '*');
            mLog.info("Password: " + new String(dummyPassword));
        }
    }

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host);

    if (auth) {
        props.put("mail.smtp.auth", "true");
    } else {
        props.put("mail.smtp.auth", "false");
    }

    if (tls) {
        props.put("mail.smtp.starttls.enable", "true");
    } else {
        props.put("mail.smtp.starttls.enable", "false");
    }

    // Disable certificate checking so we can test against
    // self-signed certificates
    props.put("mail.smtp.ssl.socketFactory", SocketFactories.dummySSLSocketFactory());

    Session session = Session.getInstance(props, null);
    session.setDebug(trace);

    try {
        // create a message
        MimeMessage msg = new ZMimeMessage(session, new ZSharedFileInputStream(file));
        InternetAddress[] address = { new JavaMailInternetAddress(recipient) };
        msg.setFrom(new JavaMailInternetAddress(sender));

        // attach the file to the message
        Transport transport = session.getTransport("smtp");
        transport.connect(null, user, password);
        transport.sendMessage(msg, address);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
        System.exit(1);
    }
}

From source file:pl.umk.mat.zawodyweb.email.EmailSender.java

public static void send(String address, String subject, String text) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    Session session = Session.getInstance(props);

    try {/*from w  w w . ja  v a  2  s .  c  om*/
        Address[] addresses = InternetAddress.parse(address);

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(addressFrom));
        message.setRecipients(Message.RecipientType.TO, addresses);
        message.setSubject(subjectPrefix + subject);
        message.setSentDate(new Date());
        message.setText(text);

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpHost, smtpPort, smtpUser, smtpPassword);

        transport.sendMessage(message, addresses);

        transport.close();
    } catch (MessagingException ex) {
        log.error(ex);
    }
}

From source file:org.xmlactions.email.EMailSend.java

public static void sendEMail(String fromAddress, String toAddress, String host, String userName,
        String password, String subject, String msg) throws AddressException, MessagingException {

    log.debug(String.format(/* w w  w  .  ja  va  2s.c om*/
            "sendEMail(from:%s, to:%s, host:%s, userName:%s, password:%s)\nsubject:{" + subject
                    + "\n}\nmessage:{" + msg + "\n}",
            fromAddress, toAddress, host, userName, toPassword(password), subject, msg));
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session;
    if (!StringUtils.isEmpty(password)) {
        props.put("mail.smtp.auth", "true");
        //EMailAuthenticator auth = new EMailAuthenticator(userName + "+" + host, password);
        EMailAuthenticator auth = new EMailAuthenticator(userName, password);
        session = Session.getInstance(props, auth);
    } else {
        session = Session.getInstance(props);
    }

    // Define message
    MimeMessage message = new MimeMessage(session);
    // message.setFrom(new InternetAddress("email_addresses@riostl.com"));
    message.setFrom(new InternetAddress(fromAddress));
    message.addRecipient(RecipientType.TO, new InternetAddress(toAddress));
    message.setSubject(subject);
    message.setText(msg);

    // Send message
    if (StringUtils.isEmpty(password)) {
        Transport.send(message);
    } else {
        Provider provider = session.getProvider("smtp");

        Transport transport = session.getTransport(provider);
        // Send message
        transport.connect();
        transport.sendMessage(message, new Address[] { new InternetAddress(toAddress) });
        transport.close();
    }

}

From source file:org.bml.util.mail.MailUtils.java

/**
 * Simple mail utility/*from w  ww  . ja  v a  2  s . c  o  m*/
 * @param sendToAdresses email addresses to send the mail to
 * @param emailSubjectLine the subject of the email.
 * @param emailBody The body of the mail
 * @param smtpHost the smtp host
 * @param sender the mail address that is the sender
 * @param smtpPassword the password for the sender
 * @param smtpPort the port to contact the smtp server on
 * @return boolean true on success and false on error
 */
public static boolean sendMail(final String[] sendToAdresses, final String emailSubjectLine,
        final String emailBody, final String smtpHost, String sender, String smtpPassword, final int smtpPort) {
    if ((sendToAdresses == null) || (sendToAdresses.length == 0)) {
        return false;
    }

    if ((emailSubjectLine == null) || (emailBody == null)) {
        return false;
    }

    try {
        Address[] addresses = new Address[sendToAdresses.length];
        for (int i = 0; i < sendToAdresses.length; i++) {
            addresses[i] = new InternetAddress(sendToAdresses[i]);
        }

        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", smtpHost);
        props.setProperty("mail.smtp.localhost", smtpHost);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.port", String.valueOf(smtpPort));
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props, null);

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.setRecipients(Message.RecipientType.TO, addresses);
        message.setSubject(emailSubjectLine);
        message.setContent(emailBody, "text/plain");
        message.saveChanges();

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpHost, sender, smtpPassword);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    } catch (Throwable t) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Error occured while sending mail.", t);
        }
        return false;
    }
    return true;
}

From source file:com.liferay.util.mail.MailEngine.java

private static void _sendMessage(Session session, Message msg) throws MessagingException {

    boolean smtpAuth = GetterUtil.getBoolean(session.getProperty("mail.smtp.auth"), false);
    String smtpHost = session.getProperty("mail.smtp.host");
    String user = session.getProperty("mail.smtp.user");
    String password = session.getProperty("mail.smtp.password");

    if (smtpAuth && Validator.isNotNull(user) && Validator.isNotNull(password)) {

        Transport tr = session.getTransport("smtp");
        tr.connect(smtpHost, user, password);
        tr.sendMessage(msg, msg.getAllRecipients());
        tr.close();//from  w  w  w  .j ava 2  s .  c  o  m
    } else {
        Transport.send(msg);
    }
}

From source file:com.medsavant.mailer.Mail.java

public synchronized static boolean sendEmail(String to, String subject, String text, File attachment) {
    try {//from  w  w w.java  2 s.c  o m

        if (src == null || pw == null || host == null || port == -1) {
            return false;
        }

        if (to.isEmpty()) {
            return false;
        }

        LOG.info("Sending email to " + to + " with subject " + subject);

        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("mail.smtp.user", src);
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.starttls.enable", starttls);
        props.put("mail.smtp.auth", auth);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", fallback);
        Session session = Session.getInstance(props, null);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(src, srcName));
        InternetAddress[] address = InternetAddress.parse(to);
        msg.setRecipients(Message.RecipientType.BCC, address);
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setContent(text, "text/html");

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);

        if (attachment != null) {
            // create the second message part
            MimeBodyPart mbp2 = new MimeBodyPart();
            // attach the file to the message
            FileDataSource fds = new FileDataSource(attachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());
            mp.addBodyPart(mbp2);
        }

        // add the Multipart to the message
        msg.setContent(mp);
        // set the Date: header
        msg.setSentDate(new Date());
        // send the message
        Transport transport = session.getTransport("smtp");
        transport.connect(host, src, pw);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

        LOG.info("Mail sent");

        return true;

    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.error(ex);
        return false;
    }

}

From source file:quickforms.sme.UseFulMethods.java

static public void sendEmail(String d_email, String pwd, String m_to, String m_subject, String message)
        throws Exception {
    final String from = d_email;
    final String password = pwd;
    class SMTPAuthenticator extends Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, password);
        }//from w  w  w  .  jav  a  2 s .  c  om
    }

    //String d_uname = "email";
    //String d_password = "password";
    String d_host = "smtp.gmail.com";
    String d_port = "465"; //465,587

    Properties props = new Properties();
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);

    //msg.setText(message);
    // Send the actual HTML message, as big as you like

    msg.setContent(message, "text/html");
    msg.setSubject(m_subject);
    msg.setFrom(new InternetAddress(from));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

    Transport transport = session.getTransport("smtps");
    transport.connect(d_host, 465, from, password);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();

}

From source file:ee.cyber.licensing.service.MailService.java

private static void sendMail(String email, String password, String host, Session getMailSession,
        MimeMessage mailMessage) throws MessagingException {
    Transport transport = getMailSession.getTransport("smtp");

    // if you have 2FA enabled then provide App Specific Password
    transport.connect(host, email, password);
    transport.sendMessage(mailMessage, mailMessage.getAllRecipients());
    transport.close();//w  ww  . ja v  a2s.  c  o  m
    logger.info("6th ===> Email Sent Successfully With Image Attachment");
    logger.info("7th ===> generateAndSendEmail() ended");
}

From source file:eu.forgestore.ws.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    if ((FStoreRepository.getPropertyByName("mailhost").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", FStoreRepository.getPropertyByName("mailhost").getValue());
    if ((FStoreRepository.getPropertyByName("mailuser").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", FStoreRepository.getPropertyByName("mailuser").getValue());
    if ((FStoreRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!FStoreRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", FStoreRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = FStoreRepository.getPropertyByName("adminEmail").getValue();
    String subj = FStoreRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;
    try {//from w ww. ja  v  a 2 s.  c o m
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:gr.upatras.ece.nam.baker.util.EmailUtil.java

public static void SendRegistrationActivationEmail(String email, String messageBody) {

    Properties props = new Properties();

    // Session session = Session.getDefaultInstance(props, null);

    props.setProperty("mail.transport.protocol", "smtp");
    if ((BakerRepository.getPropertyByName("mailhost").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailhost").getValue().isEmpty()))
        props.setProperty("mail.host", BakerRepository.getPropertyByName("mailhost").getValue());
    if ((BakerRepository.getPropertyByName("mailuser").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailuser").getValue().isEmpty()))
        props.setProperty("mail.user", BakerRepository.getPropertyByName("mailuser").getValue());
    if ((BakerRepository.getPropertyByName("mailpassword").getValue() != null)
            && (!BakerRepository.getPropertyByName("mailpassword").getValue().isEmpty()))
        props.setProperty("mail.password", BakerRepository.getPropertyByName("mailpassword").getValue());

    String adminemail = BakerRepository.getPropertyByName("adminEmail").getValue();
    String subj = BakerRepository.getPropertyByName("activationEmailSubject").getValue();
    logger.info("adminemail = " + adminemail);
    logger.info("subj = " + subj);

    Session mailSession = Session.getDefaultInstance(props, null);
    Transport transport;
    try {/*from  w  w  w . j a v a  2s .  c o m*/
        transport = mailSession.getTransport();

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setSentDate(new Date());
        msg.setFrom(new InternetAddress(adminemail, adminemail));
        msg.setSubject(subj);
        msg.setContent(messageBody, "text/html; charset=ISO-8859-1");
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));

        transport.close();

    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}