Example usage for javax.mail Transport send

List of usage examples for javax.mail Transport send

Introduction

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

Prototype

public static void send(Message msg) throws MessagingException 

Source Link

Document

Send a message.

Usage

From source file:org.awknet.commons.mail.Mail.java

public void send() throws AddressException, MessagingException, FileNotFoundException, IOException {
    int count = recipientsTo.size() + recipientsCc.size() + recipientsBcc.size();
    if (count == 0)
        return;// w  ww.j av  a2  s.  c  o m

    deleteDuplicates();

    Properties javaMailProperties = new Properties();

    if (fileName.equals("") || fileName == null)
        fileName = DEFAULT_PROPERTIES_FILE;

    javaMailProperties.load(getClass().getResourceAsStream(fileName));

    final String mailUsername = javaMailProperties.getProperty("mail.autentication.username");
    final String mailPassword = javaMailProperties.getProperty("mail.autentication.password");
    final String mailFrom = javaMailProperties.getProperty("mail.autentication.mail_from");

    Session session = Session.getInstance(javaMailProperties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(mailUsername, mailPassword);
        }
    });

    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mailFrom));
    msg.setRecipients(Message.RecipientType.TO, getToRecipientsArray());
    msg.setRecipients(Message.RecipientType.CC, getCcRecipientsArray());
    msg.setRecipients(Message.RecipientType.BCC, getBccRecipientsArray());
    msg.setSentDate(new Date());
    msg.setSubject(mailSubject);
    msg.setText(mailText, "UTF-8", "html");
    // msg.setText(mailText); //OLD WAY
    new Thread(new Runnable() {
        public void run() {
            try {
                Transport.send(msg);
                Logger.getLogger(Mail.class.getName()).log(Level.INFO, "email was sent successfully!");
            } catch (MessagingException ex) {
                Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, "Cant send email!", ex);
            }
        }
    }).start();
}

From source file:ru.org.linux.util.EmailService.java

public void sendEmail(String nick, String email, boolean isNew) throws MessagingException {
    StringBuilder text = new StringBuilder();

    text.append("?!\n\n");
    if (isNew) {//ww  w .ja  v a  2  s.co m
        text.append(
                "\t?   ? http://www.linux.org.ru/ ?? ?? ?,\n");
    } else {
        text.append(
                "\t?   ? http://www.linux.org.ru/   ?? ?,\n");
    }

    text.append("     ? ? (e-mail).\n\n");
    text.append(
            "  ?    ? ? ?: '");
    text.append(nick);
    text.append("'\n\n");
    text.append(
            "?   ,     - ?  ? ?!\n\n");

    if (isNew) {
        text.append(
                "?     ???    ? http://www.linux.org.ru/,\n");
        text.append(
                "  ?  ? ?   ?    ?.\n\n");
    } else {
        text.append(
                "?      ? ? ? http://www.linux.org.ru/,\n");
        text.append("  ?  ? .\n\n");
    }

    String regcode = User.getActivationCode(configuration.getSecret(), nick, email);

    text.append(
            "?    ?? http://www.linux.org.ru/activate.jsp\n\n");
    text.append(" : ").append(regcode).append("\n\n");
    text.append("  ?!\n");

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));

    emailMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
    emailMessage.setSubject("Linux.org.ru registration");
    emailMessage.setSentDate(new Date());
    emailMessage.setText(text.toString(), "UTF-8");

    Transport.send(emailMessage);
}

From source file:domain.Employee.java

private String newPassword(String email) {

    if (email.equals("")) {
        throw new IllegalArgumentException("email must not be null");
    }//from   w  ww.j  ava  2 s .  c  o m
    String pass = RandomStringUtils.randomAlphanumeric(8);
    //email the employee the password they can use to login

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

    String messagebody = String.format(
            "Dear %s %n" + "%n" + "Your account is now ready to login and submit availibility at URL %n" + "%n"
                    + "login: %s %n" + "password: %s %n" + "%n" + "Regards," + "Administration",
            getName(), getEmail(), pass);
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("admin@poised-resource-99801.appspotmail.com", "Administration"));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(getEmail(), getName()));
        msg.setSubject("Your account has been activated");
        msg.setText(messagebody);
        Transport.send(msg);
    } catch (MessagingException | UnsupportedEncodingException ex) {
        Logger.getLogger(Employee.class.getName()).log(Level.SEVERE, null, ex);
    }
    //hash the string and set the employee's password to the hashed one. USED SHA256
    System.out.println(pass);
    String hash = DigestUtils.sha256Hex(pass);
    return hash;
}

From source file:com.intuit.tank.mail.TankMailer.java

/**
 * @{inheritDoc/*  w  ww  . ja  va2  s .c o  m*/
 */
@Override
public void sendMail(MailMessage message, String... emailAddresses) {
    MailConfig mailConfig = new TankConfig().getMailConfig();
    Properties props = new Properties();
    props.put("mail.smtp.host", mailConfig.getSmtpHost());
    props.put("mail.smtp.port", mailConfig.getSmtpPort());

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
        fromAddress = new InternetAddress(mailConfig.getMailFrom());
        simpleMessage.setFrom(fromAddress);
        for (String email : emailAddresses) {
            try {
                toAddress = new InternetAddress(email);
                simpleMessage.addRecipient(RecipientType.TO, toAddress);
            } catch (AddressException e) {
                LOG.warn("Error with recipient " + email + ": " + e.toString());
            }
        }

        simpleMessage.setSubject(message.getSubject());
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(message.getPlainTextBody(), "text/plain");
        textPart.setHeader("MIME-Version", "1.0");
        textPart.setHeader("Content-Type", textPart.getContentType());
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        // htmlPart.setContent(message.getHtmlBody(), "text/html");
        htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody())));
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html");
        // Create the Multipart. Add BodyParts to it.
        final Multipart mp = new MimeMultipart("alternative");
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        // Set Multipart as the message's content
        simpleMessage.setContent(mp);
        simpleMessage.setHeader("MIME-Version", "1.0");
        simpleMessage.setHeader("Content-Type", mp.getContentType());
        logMsg(mailConfig.getSmtpHost(), simpleMessage);
        if (simpleMessage.getRecipients(RecipientType.TO) != null
                && simpleMessage.getRecipients(RecipientType.TO).length > 0) {
            Transport.send(simpleMessage);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.freemarker.mail.GMail.java

public boolean sendMailUsingJavaMailAPI(String to, String message1, HttpServletRequest req, String mid,
        String createdby, String pname, String mname) {
    String FinalMessage = new FreeMarkerMailTemplateCreater().createAndReturnTemplateDataMapping(message1,
            getTemplateLocation(req), mid, createdby, pname, mname);
    String from = "analytixdstest@gmail.com";
    final String username = "analytixdstest@gmail.com";
    final String password = "analytix000";
    String host = "smtp.gmail.com";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from www  .ja v a 2s .com*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setContent(FinalMessage, "text/html; charset=utf-8");
        message.saveChanges();
        message.setSubject("Analytix Test Mail");
        Transport.send(message);
        return true;
    } catch (MessagingException e) {
        return false;

    }
}

From source file:com.angstoverseer.service.mail.MailServiceImpl.java

private void sendResponseMail(final Address sender, final String answer, final String subject)
        throws Exception {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    Message mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress("overseer@thenewoverseer.appspotmail.com", "Overseer"));
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(sender.toString()));
    mimeMessage.setSubject("Re: " + subject);
    mimeMessage.setText(answer);//from  w w  w  .jav a2 s  . co m
    Transport.send(mimeMessage);
}

From source file:pt.webdetails.cdv.notifications.EmailOutlet.java

private boolean email(Alert alert) {

    try {//  w  ww  .  j av a  2 s. co  m

        // Get the session object
        final Session session = buildSession();

        // Create the message
        final MimeMessage msg = new MimeMessage(session);

        // From, to, etc.
        applyMessageHeaders(msg, alert);

        // Get main message multipart
        final Multipart multipartBody = getMultipartBody(session, alert);

        // Process attachments
        //final Multipart mainMultiPart = processAttachments(multipartBody);
        //msg.setContent(mainMultiPart);
        msg.setContent(multipartBody);

        // Send it

        //msg.setHeader("X-Mailer", MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;

    } catch (SendFailedException e) {
        logger.error(e);
    } catch (AuthenticationFailedException e) {
        logger.error(e);
    } catch (MessagingException me) {
        logger.error(me);
    } catch (IOException e) {
        logger.error(e);
    }

    return false;
}

From source file:com.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from  w  ww.jav  a 2  s  .  c o  m
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

From source file:com.assetmanager.service.mail.MailService.java

/**
 * Sends the activation e-mail to the given user.
 *
 * @param user the user/*from w w  w  . ja  v  a2  s . c  o  m*/
 * @param locale the locale
 * @throws MessagingException messaging exception
 */
public final void sendActivationEmail(final UserAccount user, final String locale) throws MessagingException {
    final Properties props = new Properties();
    final Session session = Session.getDefaultInstance(props, null);
    final Message message = new MimeMessage(session);
    final Multipart multipart = new MimeMultipart();
    final MimeBodyPart htmlPart = new MimeBodyPart();
    final MimeBodyPart textPart = new MimeBodyPart();

    message.setFrom(new InternetAddress(getFromAddress()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));

    message.setSubject(messageSource.getMessage("mail.subject", null, new Locale(locale)));

    textPart.setContent(messageSource.getMessage("mail.body.txt",
            new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/plain");

    htmlPart.setContent(messageSource.getMessage("mail.body.html",
            new Object[] { getHostname(), user.getActivationKey() }, new Locale(locale)), "text/html");

    multipart.addBodyPart(textPart);
    multipart.addBodyPart(htmlPart);
    message.setContent(multipart);

    Transport.send(message);
}

From source file:com.app.mail.DefaultMailSender.java

@Override
public void sendPaymentFailedMessage(String emailAddress) {
    Session session = _authenticateOutboundEmailAddress();

    try {//from   ww w  .j  a v  a 2s. com
        Message emailMessage = _populateMessage(emailAddress, "Payment Failed", "payment_failed_email.vm",
                session);

        Transport.send(emailMessage);
    } catch (Exception e) {
        _log.error("Unable to send payment failed message", e);
    }
}