Example usage for javax.mail.internet MimeMessage setRecipients

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

Introduction

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

Prototype

public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException 

Source Link

Document

Set the specified recipient type to the given addresses.

Usage

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Sends an email in text-format in iso-8859-1-encoding
 * /*from w ww  .ja  v  a 2s  . co  m*/
 * @param subject the subject of the new mail
 * @param message the content of the mail
 * @param from the sender-address
 * @param to the receiver-address(es)
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendMail(String subject, String message, String from, String[] to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        for (int i = to.length - 1; i >= 0; i--) {
            msg.addRecipients(Message.RecipientType.TO, to[i]);
        }
        msg.setSubject(subject, "iso-8859-1");
        msg.setSentDate(new Date());
        msg.setText(message, "iso-8859-1");
        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending mail: " + e.getLocalizedMessage());
    }
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * // ww w .jav  a  2  s.c  o  m
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "iso-8859-1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart();
        BodyPart bodyPart = new MimeBodyPart();

        bodyPart.setText(alternativeTextMessage);
        multiPart.addBodyPart(bodyPart);

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(htmlMessage, "text/html");
        multiPart.addBodyPart(bodyPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * /*w w  w  . j  a  v a2 s.  com*/
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "ISO8859_1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart("alternative");
        MimeBodyPart htmlPart = new MimeBodyPart();
        MimeBodyPart textPart = new MimeBodyPart();

        textPart.setText(alternativeTextMessage, "ISO8859_1");
        textPart.setHeader("MIME-Version", "1.0");
        //textPart.setHeader("Content-Type", textPart.getContentType());
        textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\"");

        htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\"");
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\"");
        //htmlPart.setHeader("Content-Type", htmlPart.getContentType());

        multiPart.addBodyPart(textPart);
        multiPart.addBodyPart(htmlPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        msg.setHeader("MIME-Version", "1.0");
        msg.setHeader("Content-Type", multiPart.getContentType());

        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifyAccountDeleted(TemporaryMailContainer container) {
    try {/*from  w  w w  .j  a  v a  2  s  .c o m*/
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s

        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s,<br><br>Your account has been deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted.subject"));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java

public static void notifySubscriptionDeleted(TemporaryMailContainer container) {
    try {/*from ww  w. j  a va 2s  .  c o  m*/
        Publisher publisher = container.getPublisher();
        Publisher deletedBy = container.getDeletedBy();
        Subscription obj = container.getObj();
        String emailaddress = publisher.getEmailAddress();
        if (emailaddress == null || emailaddress.trim().equals(""))
            return;
        Properties properties = new Properties();
        Session session = null;
        String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX,
                Property.DEFAULT_JUDDI_EMAIL_PREFIX);
        if (!mailPrefix.endsWith(".")) {
            mailPrefix = mailPrefix + ".";
        }
        for (String key : mailProps) {
            if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) {
                properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key));
            } else if (System.getProperty(mailPrefix + key) != null) {
                properties.put(key, System.getProperty(mailPrefix + key));
            }
        }

        boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true");
        if (auth) {
            final String username = properties.getProperty("mail.smtp.user");
            String pwd = properties.getProperty("mail.smtp.password");
            //decrypt if possible
            if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false")
                    .equalsIgnoreCase("true")) {
                try {
                    pwd = CryptorFactory.getCryptor().decrypt(pwd);
                } catch (NoSuchPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (NoSuchAlgorithmException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidAlgorithmParameterException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (InvalidKeyException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (IllegalBlockSizeException ex) {
                    log.error("Unable to decrypt settings", ex);
                } catch (BadPaddingException ex) {
                    log.error("Unable to decrypt settings", ex);
                }
            }
            final String password = pwd;
            log.debug("SMTP username = " + username + " from address = " + emailaddress);
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(properties, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        } else {
            Properties eMailProperties = properties;
            eMailProperties.remove("mail.smtp.user");
            eMailProperties.remove("mail.smtp.password");
            session = Session.getInstance(eMailProperties);
        }

        MimeMessage message = new MimeMessage(session);
        InternetAddress address = new InternetAddress(emailaddress);
        Address[] to = { address };
        message.setRecipients(RecipientType.TO, to);
        message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI")));
        //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s
        //maybe nice to use a template rather then sending raw xml.
        org.uddi.sub_v3.Subscription api = new org.uddi.sub_v3.Subscription();
        MappingModelToApi.mapSubscription(obj, api);
        String subscriptionResultXML = JAXBMarshaller.marshallToString(api, JAXBMarshaller.PACKAGE_SUBSCR_RES);
        Multipart mp = new MimeMultipart();

        MimeBodyPart content = new MimeBodyPart();
        String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.subscriptionDeleted");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ");
        //Hello %s, %s<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s.
        msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()),
                StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()),
                StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()),
                StringEscapeUtils.escapeHtml(sdf.format(new Date())),
                StringEscapeUtils.escapeHtml(
                        AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"),
                AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)"));

        content.setContent(msg_content, "text/html; charset=UTF-8;");
        mp.addBodyPart(content);

        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
        attachment.setFileName("uddiNotification.xml");
        mp.addBodyPart(attachment);

        message.setContent(mp);
        message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " "
                + StringEscapeUtils.escapeHtml(obj.getSubscriptionKey()));
        Transport.send(message);

    } catch (Throwable t) {
        log.warn("Error sending email!" + t.getMessage());
        log.debug("Error sending email!" + t.getMessage(), t);
    }
}

From source file:jp.mamesoft.mailsocketchat.Mail.java

public static void Send(String to, int mode) {
    //mode 0 = ?, 1 = ?, 2 = ?, 3 = ??, 4 = , 5 = 
    System.out.println("???");
    String from = Mailsocketchat.mail_user;
    String host = "smtp.gmail.com";
    String port = "465";
    String text = "";
    String subject = "";
    if (mode == 0) {
        text = logprint(text);/* www. j  a  v  a  2s . c  o  m*/
        subject = " - MailSocketChat";
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }
    if (mode == 1) {
        if (Mailsocketchat.subjectname) {
            subject = Mailsocketchat.logs.get(0).get("name");
        } else {
            subject = "?? - MailSocketChat";
        }
        text = logprint(text);
    }
    if (mode == 8) {
        text = logprint(text);
        subject = "?? - MailSocketChat";
    }
    if (mode == 2) {

        if (!Mailsocketchat.push) {
            subject = "????? - MailSocketChat";
            text = "???????????????????\n\n??????\n";
            text = logprint(text);
        } else {
            subject = "??? - MailSocketChat";
            text = "?????????????????\n(???????????)\n\n";
        }
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }
    if (mode == 3) {

        if (!Mailsocketchat.push && !Mailsocketchat.repeat) {
            subject = "???? - MailSocketChat";
            text = "????\n\n??????\n";
            text = logprint(text);
        } else {
            subject = "?????? - MailSocketChat";
            text = "?????????????????\n\n";
            if (Mailsocketchat.repeat) {
                text = text + "??????\n";
                text = logprint(text);
            }
        }
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }

    if (mode == 7) {

        if (!Mailsocketchat.repeat) {
            subject = "????? - MailSocketChat";
            text = "?????30????????????\n\n";
            if (!Mailsocketchat.push) {
                text = text + "??????\n";
                text = logprint(text);
            }
        } else {
            subject = "??? - MailSocketChat";
            text = "???\n\n";
        }
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }

    if (mode == 4) {
        subject = " - MailSocketChat";

        int userint = Mailsocketchat.users.size();
        int romint = Mailsocketchat.roms.size();
        text = ": " + userint + " ROM: " + romint + "\n\n\n";

        for (Integer id : Mailsocketchat.users.keySet()) {
            HashMap<String, String> data = Mailsocketchat.users.get(id);
            text = text + data.get("name") + "\n";
            text = text + " (" + data.get("ip") + ")\n";
        }

        text = text + "\n\nROM\n";
        for (Integer id : Mailsocketchat.roms.keySet()) {
            HashMap<String, String> data = Mailsocketchat.roms.get(id);
            text = text + data.get("ip") + "\n";
        }
        if (Mailsocketchat.newver) {
            text = text + "\n\n??????????\n";
        }
    }
    if (mode == 5) {
        subject = " - MailSocketChat";
        if (Mailsocketchat.push) {
            text = "??: \n\n";
        } else if (Mailsocketchat.repeat) {
            text = "??: \n\n";
        } else {
            text = "??: ?\n\n";
        }
        text = text + "?\n";
        text = text + "?(fetch): ?????\n";
        text = text + "(push): ????\n";
        text = text + "(repeat): ????\n";
        text = text + "(list): ???\n";
        text = text + "#: ?????\n";
        text = text + "#hoge: ??hoge????\n";
        text = text + "(help): ?????\n\n";

        text = text + "\nMailSocketChat Ver." + Mailsocketchat.version + "\n";
        if (Mailsocketchat.newver) {
            text = text + "??????????\n";
        }
    }
    if (mode == 6) {
        subject = "????????? - MailSocketChat";
        text = text
                + "MailSocketChat??????????????????\n";
    }

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);

    Session sendsession = Session.getInstance(props,
            new PlainAuthenticator(Mailsocketchat.mail_user, Mailsocketchat.mail_pass));

    try {
        // create a message
        MimeMessage msg = new MimeMessage(sendsession);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] sendaddress = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, sendaddress);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(text);

        Transport.send(msg);
        System.out.println("?????");
    } catch (MessagingException mex) {
        System.out.println("??????");
    }
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Sends a mail message. The content must be provided as MimeBodyPart objects.
 *
 * @param from      Sender's email address.
 * @param to        Recipient's email address.
 * @param cc        Email address for CC.
 * @param bcc       Email address for BCC.
 * @param subject   Subject text for the email.
 * @param bodyParts The body parts to insert into the message.
 * @throws SystemException        if an unexpected error occurs.
 * @throws ConfigurationException if a configuration error occurs.
 *///from www .  ja v a  2  s.co m
public static void send(String from, String to, String cc, String bcc, String subject, MimeBodyPart[] bodyParts)
        throws ConfigurationException, SystemException {

    initEventLog();

    try {
        Properties props = new Properties();

        Configuration config = Aksess.getConfiguration();
        String host = config.getString("mail.host");
        if (host == null) {
            throw new ConfigurationException("mail.host");
        }

        // I noen tilfeller nsker vi at all epost skal g til en testadresse
        String catchAllTo = config.getString("mail.catchall.to");
        boolean catchallExists = catchAllTo != null && catchAllTo.contains("@");
        if (catchallExists) {
            StringBuilder prefix = new StringBuilder(" (original recipient: " + to);
            if (cc != null) {
                prefix.append(", cc: ").append(cc);
            }
            if (bcc != null) {
                prefix.append(", bcc: ").append(bcc);
            }
            prefix.append(") ");
            subject = prefix + subject;
            to = catchAllTo;
            cc = null;
            bcc = null;
        }

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

        Session session = Session.getDefaultInstance(props);

        boolean debug = config.getBoolean("mail.debug", false);
        if (debug) {
            session.setDebug(true);
        }

        // Opprett message, sett attributter
        MimeMessage message = new MimeMessage(session);
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress[] = InternetAddress.parse(to);

        message.setFrom(fromAddress);

        if (toAddress.length > 1) {
            message.setRecipients(Message.RecipientType.BCC, toAddress);
        } else {
            message.setRecipients(Message.RecipientType.TO, toAddress);
        }
        if (cc != null) {
            message.addRecipients(Message.RecipientType.CC, cc);
        }
        if (bcc != null) {
            message.addRecipients(Message.RecipientType.BCC, bcc);
        }

        message.setSubject(subject, "ISO-8859-1");
        message.setSentDate(new Date());

        Multipart mp = new MimeMultipart();
        for (MimeBodyPart bodyPart : bodyParts) {
            mp.addBodyPart(bodyPart);
        }
        message.setContent(mp);

        // Send meldingen
        Transport.send(message);

        eventLog.log("System", null, Event.EMAIL_SENT, to + ":" + subject, null);

        // Logg sending
        log.info("Sending email to " + to + " with subject " + subject);
    } catch (MessagingException e) {
        String errormessage = "Subject: " + subject + " | Error: " + e.getMessage();
        eventLog.log("System", null, Event.FAILED_EMAIL_SUBMISSION, errormessage + " | to: " + to, null);
        log.error("Error sending mail", e);
        throw new SystemException("Error sending email to : " + to + " with subject " + subject, e);
    }
}

From source file:gmailclientfx.core.GmailClient.java

public static void sendMessage(String to, String subject, String body, List<String> attachments)
        throws Exception {
    // authenticate with gmail smtp server
    SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true);

    // kreiraj MimeMessage objekt
    MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession());

    // dodaj headere
    msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");

    msg.setFrom(new InternetAddress(EMAIL));
    msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to));
    msg.setSubject(subject, "UTF-8");
    msg.setReplyTo(InternetAddress.parse(EMAIL, false));

    // tijelo poruke
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setText(body);/*w w w.  java  2  s. com*/

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(msgBodyPart);
    msg.setContent(multipart);

    // dodaj privitke
    if (attachments.size() > 0) {
        for (String attachment : attachments) {
            msgBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            msgBodyPart.setDataHandler(new DataHandler(source));
            msgBodyPart.setFileName(source.getName());
            multipart.addBodyPart(msgBodyPart);
        }
        msg.setContent(multipart);
    }
    smtpTransport.sendMessage(msg, InternetAddress.parse(to));

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Poruka poslana!");
    alert.setHeaderText(null);
    alert.setContentText("Email uspjeno poslan!");
    alert.showAndWait();
}

From source file:com.flexive.shared.FxMailUtils.java

/**
 * Sends an email/*w  w  w  . j  a va 2s.com*/
 *
 * @param SMTPServer      IP Address of the SMTP server
 * @param subject         subject of the email
 * @param textBody        plain text
 * @param htmlBody        html text
 * @param to              recipient
 * @param cc              cc recepient
 * @param bcc             bcc recipient
 * @param from            sender
 * @param replyTo         reply-to address
 * @param mimeAttachments strings containing mime encoded attachments
 * @throws FxApplicationException on errors
 */
public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to,
        String cc, String bcc, String from, String replyTo, String... mimeAttachments)
        throws FxApplicationException {

    try {
        // Set the mail server
        java.util.Properties properties = System.getProperties();
        if (SMTPServer != null)
            properties.put("mail.smtp.host", SMTPServer);

        // Get a session and create a new message
        javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
        MimeMessage msg = new MimeMessage(session);

        // Set the sender
        if (StringUtils.isBlank(from))
            msg.setFrom(); // Uses local IP Adress and the user under which the server is running
        else {
            msg.setFrom(createAddress(from));
        }

        if (!StringUtils.isBlank(replyTo))
            msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false)));

        // Set the To, Cc and Bcc fields
        if (!StringUtils.isBlank(to))
            msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false)));
        if (!StringUtils.isBlank(cc))
            msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false)));
        if (!StringUtils.isBlank(bcc))
            msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false)));

        // Set the subject
        msg.setSubject(subject, "UTF-8");

        String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"";

        StringBuilder body = new StringBuilder(5000);

        if (mimeAttachments.length > 0) {
            sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\"";
            body.append("This is a multi-part message in MIME format.\n\n");
            body.append("--" + BOUNDARY2 + "\n");
            body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n");
        }

        if (textBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/plain; charset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            body.append(encodeQuotedPrintable(textBody)).append("\n");
        }
        if (htmlBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            if (htmlBody.toLowerCase().indexOf("<html>") < 0) {
                body.append("<HTML><HEAD>\n<TITLE></TITLE>\n");
                body.append(
                        "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n");
                body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n");
            } else
                body.append(encodeQuotedPrintable(htmlBody)).append("\n");
        }

        body.append("\n--" + BOUNDARY1 + "--\n");

        if (mimeAttachments.length > 0) {
            for (String mimeAttachment : mimeAttachments) {
                body.append("\n--" + BOUNDARY2 + "\n");
                body.append(mimeAttachment).append("\n");
            }
            body.append("\n--" + BOUNDARY2 + "--\n");
        }

        msg.setDataHandler(
                new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType)));

        // Set the header
        msg.setHeader("X-Mailer", "JavaMailer");

        // Set the sent date
        msg.setSentDate(new java.util.Date());

        // Send the message
        javax.mail.Transport.send(msg);
    } catch (AddressException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef());
    } catch (javax.mail.MessagingException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (IOException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (EncoderException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    }
}

From source file:nu.mine.kino.jenkins.plugins.projectmanagement.utils.PMUtils.java

public static void sendMail(String[] addresses, String subject, String message)
        throws UnsupportedEncodingException, MessagingException {

    MimeMessage mimeMessage = new MimeMessage(Mailer.descriptor().createSession());
    String adminAddress = JenkinsLocationConfiguration.get().getAdminAddress();

    InternetAddress[] to = new InternetAddress[addresses.length];
    for (int i = 0; i < addresses.length; i++) {
        to[i] = new InternetAddress(addresses[i], true);
    }//from  w  w w .  j  a  va  2  s .c o m
    mimeMessage.setSender(new InternetAddress(adminAddress));
    mimeMessage.setRecipients(Message.RecipientType.TO, to);
    mimeMessage.setSubject(subject, "ISO-2022-JP");
    mimeMessage.setText(message, "ISO-2022-JP");
    Transport.send(mimeMessage);
}