Example usage for javax.mail.internet MimeMessage MimeMessage

List of usage examples for javax.mail.internet MimeMessage MimeMessage

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage MimeMessage.

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

Constructs a new MimeMessage with content initialized from the source MimeMessage.

Usage

From source file:com.gcrm.util.mail.MailService.java

public void sendSystemSimpleMail(String toAddress, String subject, String text) throws Exception {
    List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName());
    EmailSetting emailSetting = null;//from  w ww  .ja v a 2s  .c  om
    if (emailSettings != null && emailSettings.size() > 0) {
        emailSetting = emailSettings.get(0);
    } else {
        return;
    }
    Session mailSession = this.createSmtpSession(emailSetting);
    if (mailSession != null) {
        Transport transport = mailSession.getTransport();
        MimeMessage msg = new MimeMessage(mailSession);
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
        helper.setFrom(emailSetting.getFrom_address());
        helper.setTo(toAddress);
        helper.setSubject(subject);
        helper.setText(text, true);
        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
    }
}

From source file:com.hiperium.bo.manager.mail.EmailMessageManager.java

/**
 * Sends an email with the new user password.
 * /*from   w ww.  j a va2  s  .c om*/
 * @param user
 * @throws javax.mail.internet.AddressException
 * @throws javax.mail.MessagingException
 */
public void sendNewPassword(User user) {
    try {
        this.log.debug("sendNewPassword() - START");
        // Create the corresponding user locale.
        Locale locale = null;
        if (StringUtils.isBlank(user.getLanguageId())) {
            locale = Locale.getDefault();
        } else {
            locale = new Locale(user.getLanguageId());
        }
        ResourceBundle resource = ResourceBundle.getBundle(EnumI18N.COMMON.value(), locale);

        // Get system properties
        Properties properties = System.getProperties();
        // Setup mail server
        properties.setProperty("mail.smtp.host", CloudEmailUser.HOST);
        properties.setProperty("mail.user", CloudEmailUser.USERNAME);
        properties.setProperty("mail.password", CloudEmailUser.PASSWORD);
        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(CloudEmailUser.ADDRESS));
        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
        // Set Subject: header field
        message.setSubject(resource.getString(GENERATED_USER_PASSWD_SUBJECT));
        // Send the actual HTML message, as big as you like
        message.setContent(MessageFormat.format(resource.getString(GENERATED_USER_PASSWD_CONTENT),
                user.getFirstname(), user.getLastname(), user.getPassword()), "text/html");
        // Send message
        Transport.send(message);
        this.log.debug("sendNewPassword() - END");
    } catch (AddressException e) {
        this.log.error("AddressException to send email to " + user.getEmail(), e);
    } catch (MessagingException e) {
        this.log.error("MessagingException to send email to " + user.getEmail(), e);
    }
}

From source file:pmp.springmail.TestDrive.java

void sendEmailViaPlainMail(String text) {
    Authenticator authenticator = new Authenticator() {

        @Override//from   w  w w.  j  ava 2 s  .  co  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(USER, PASS);
        }
    };

    Session session = Session.getInstance(props, authenticator);
    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(FROM));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        message.setSubject("Plain JavaMail Test");
        message.setText(DATE_FORMAT.format(new Date()) + " " + text);

        Transport.send(message);

    } catch (Exception e) {
        System.err.println(e.getClass().getSimpleName() + " " + e.getMessage());
    }
}

From source file:com.gazbert.bxbot.core.mail.EmailAlerter.java

public void sendMessage(String subject, String msgContent) {

    if (sendEmailAlertsEnabled) {

        final Session session = Session.getInstance(smtpProps, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpConfig.getAccountUsername(),
                        smtpConfig.getAccountPassword());
            }/* w  w w.j av  a 2 s .c o m*/
        });

        try {
            final Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(smtpConfig.getFromAddress()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpConfig.getToAddress()));
            message.setSubject(subject);
            message.setText(msgContent);

            LOG.info(() -> "About to send following Email Alert with message content: " + msgContent);
            Transport.send(message);

        } catch (MessagingException e) {
            // not much we can do here, especially if the alert was critical - the bot is shutting down; just log it.
            LOG.error("Failed to send Email Alert. Details: " + e.getMessage(), e);
        }
    } else {
        LOG.warn("Email Alerts are disabled. Not sending the following message: Subject: " + subject
                + " Content: " + msgContent);
    }
}

From source file:com.unilever.audit.services2.ForgetPassword.java

@GET
@Path("Email/{email}")
@Produces("application/json")
public String LoginIn(@PathParam("email") String email) throws IOException {
    boolean status = true;
    String error = null;//ww  w.j a v a  2 s  . c om
    JSONObject result = new JSONObject();

    Map<String, Object> hm = new HashMap<String, Object>();
    hm.put("email", email);
    Merchandisers merchidisers = (Merchandisers) merchandisersFacadeREST
            .findOneByQuery("Merchandisers.findByEmail", hm);
    if (merchidisers == null) {
        status = false;
        error = "invalid email";
    } else {
        Properties props = new Properties();
        final String from = "";
        final String password = "";
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });
        session.setDebug(true);
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom();
            msg.setRecipients(Message.RecipientType.TO, email);
            msg.setSubject("Unilever Confirmation");
            msg.setSentDate(new Date());
            msg.setText("");
            Transport.send(msg);
        } catch (MessagingException ex) {
            //  status = false;
            //  error="Error Sending Email";
            ex.printStackTrace();
        }
    }
    result.put("status", status);
    result.put("error", error);
    System.out.println("----------------" + result.toString());
    return result.toString();
}

From source file:com.cloudbees.demo.beesshop.service.MailService.java

public void sendOrderConfirmation(ShoppingCart shoppingCart, String recipient) {

    try {//from w  w  w  . j av  a 2s  .c o m
        Message msg = new MimeMessage(mailSession);

        msg.setFrom(fromAddress);
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        msg.setSubject("[BeesShop] Order Confirmation: " + shoppingCart.getItems() + " items - "
                + shoppingCart.getPrettyPrice());

        String message = "ORDER CONFIRMATION\n" + "\n" + "* Purchased items: " + shoppingCart.getItemsCount()
                + "\n" + "* Price: " + shoppingCart.getPrettyPrice() + "\n";

        for (ShoppingCart.ShoppingCartItem item : shoppingCart.getItems()) {
            message += "   * " + item.getQuantity() + "x" + item.getProduct().getName() + "\n";
        }

        msg.setContent(message, "text/plain");

        Transport.send(msg);
        auditLogger.info("Sent to {} shopping cart with value of '{}'", recipient,
                shoppingCart.getPrettyPrice());
        sentEmailCounter.incrementAndGet();
    } catch (MessagingException e) {
        logger.warn("Exception sending order confirmation email to {}", recipient, e);
    }
}

From source file:org.tsm.concharto.service.EmailService.java

/**
 *
 * @param subject//from  www. ja v a2s .  c  om
 * @param body
 * @param sender
 * @param recipients
 */
public void SendIndividualMessages(String subject, String body, InternetAddress sender, String[] recipients) {
    int emailErrorCount = 0;
    for (int i = 0; i < recipients.length; i++) {
        String recipientEmailAddress = recipients[i];
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
        try {
            message.setText(body);
            message.setSubject(subject);
            message.setFrom(sender);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmailAddress));
            sendMessage(message);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            emailErrorCount++;
        }
    }
    if (emailErrorCount > 0) {
        String message = emailErrorCount + " out of " + recipients.length + " emails could not be sent.";
        log.error(message);
    }
}

From source file:NotificationMessage.java

static void sendMail(String toUser, Severity s) {
    // Recipient's email ID needs to be mentioned.
    //String to = "abhiyank@gmail.com";//change accordingly

    // Sender's email ID needs to be mentioned
    String from = "mdtprojectteam16@gmail.com";//change accordingly
    final String username = "mdtprojectteam16";//change accordingly
    final String password = "mdtProject16";//change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    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");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/* w  w w  .j a va  2  s  . c o  m*/
    });

    try {
        // Create a default MimeMessage object.
        javax.mail.Message message1 = new MimeMessage(session);

        // Set From: header field of the header.
        message1.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message1.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));

        // Set Subject: header field
        message1.setSubject("Alert Message From Patient");

        // Now set the actual message
        message1.setText(messageMap.get(s));

        // Send message
        Transport.send(message1);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.pinterest.deployservice.email.SMTPMailManagerImpl.java

public void send(String to, String title, String message) throws Exception {
    Session session = Session.getDefaultInstance(properties, getAuthenticator());
    // Create a default MimeMessage object.
    MimeMessage mimeMessage = new MimeMessage(session);
    // Set From: header field of the header.
    mimeMessage.setFrom(new InternetAddress(adminAddress));
    // Set To: header field of the header.
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    // Set Subject: header field
    mimeMessage.setSubject(title);/*  ww w. ja va2  s. c o m*/
    // Now set the actual message
    mimeMessage.setText(message);
    // Send message
    Transport.send(mimeMessage);
}

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

/**
 * Sends the activation e-mail to the given user.
 *
 * @param user the user/* w  w w .  j a 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);
}