Example usage for javax.mail.internet InternetAddress parse

List of usage examples for javax.mail.internet InternetAddress parse

Introduction

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

Prototype

public static InternetAddress[] parse(String addresslist) throws AddressException 

Source Link

Document

Parse the given comma separated sequence of addresses into InternetAddress objects.

Usage

From source file:org.obm.sync.server.mailer.EventChangeMailerTest.java

private List<InternetAddress> createAddressList(String addresses) throws AddressException {
    return ImmutableList.copyOf(InternetAddress.parse(addresses));
}

From source file:com.epam.ta.reportportal.util.email.EmailService.java

private boolean isAddressValid(String from) {
    try {//from ww  w . j ava2s.co  m
        InternetAddress.parse(from);
        return true;
    } catch (AddressException e) {
        return false;
    }
}

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 . j  av a  2s . c o  m*/

    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:io.uengine.mail.MailAsyncService.java

@Async
public void sendBySmtp(String subject, String text, String fromUser, String fromName, final String toUser,
        String telephone, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map<String, Object> model = new HashMap<>();
    model.put("subject", subject);
    model.put("message", text);
    model.put("name", fromName);
    model.put("email", fromUser);
    model.put("telephone", telephone);

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/contactus.vm", "UTF-8",
            model);/*from   w w  w.j  av a  2  s . co m*/
    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        Message message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        //            message.setText(text);
        message.setContent(body, "text/html;charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:org.socraticgrid.hl7.ucs.nifi.processor.SendEmail.java

private String sendEmail(String emailSubject, String fromEmail, String toEmail, String emailBody,
        String mimeType, String charset, String smtpServerUrl, String smtpServerPort, String username,
        String password, ServiceStatusController serviceStatusControllerService) throws Exception {

    String statusMessage = "Email sent successfully to " + toEmail;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpServerUrl);
    props.put("mail.smtp.port", smtpServerPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from w  w  w  .j a va 2  s.com
    });
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(emailSubject);
        message.setContent(emailBody, mimeType + "; charset=" + charset);
        Transport.send(message);
        getLogger().info("Email sent successfully!");
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.AVAILABLE);
    } catch (MessagingException e) {
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.UNAVAILABLE);
        getLogger().error("Unable to send Email! Reason : " + e.getMessage(), e);
        statusMessage = "Unable to send Email! Reason : " + e.getMessage();
        throw new RuntimeException(e);
    }
    return statusMessage;
}

From source file:org.apache.axis2.transport.mail.MailTransportSender.java

/**
 * Populate email with a SOAP formatted message
 * @param outInfo the out transport information holder
 * @param msgContext the message context that holds the message to be written
 * @throws AxisFault on error/*ww w .j  av a2  s  .c o  m*/
 * @return id of the send mail message
 */
private String sendMail(MailOutTransportInfo outInfo, MessageContext msgContext)
        throws AxisFault, MessagingException, IOException {

    OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
    // Make sure that non textual attachements are sent with base64 transfer encoding
    // instead of binary.
    format.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS, true);

    MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext);

    if (log.isDebugEnabled()) {
        log.debug(
                "Creating MIME message using message formatter " + messageFormatter.getClass().getSimpleName());
    }

    WSMimeMessage message = null;
    if (outInfo.getFromAddress() != null) {
        message = new WSMimeMessage(session, outInfo.getFromAddress().getAddress());
    } else {
        message = new WSMimeMessage(session, "");
    }

    Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (log.isDebugEnabled() && trpHeaders != null) {
        log.debug("Using transport headers: " + trpHeaders);
    }

    // set From address - first check if this is a reply, then use from address from the
    // transport out, else if any custom transport headers set on this message, or default
    // to the transport senders default From address        
    if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + outInfo.getFromAddress().getAddress()
                    + " from OutTransportInfo");
        }
        message.setFrom(outInfo.getFromAddress());
        message.setReplyTo((new Address[] { outInfo.getFromAddress() }));
    } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) {
        InternetAddress from = new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM));
        if (log.isDebugEnabled()) {
            log.debug("Setting From header to " + from.getAddress() + " from transport headers");
        }
        message.setFrom(from);
        message.setReplyTo(new Address[] { from });
    } else {
        if (smtpFromAddress != null) {
            if (log.isDebugEnabled()) {
                log.debug("Setting From header to " + smtpFromAddress.getAddress()
                        + " from transport configuration");
            }
            message.setFrom(smtpFromAddress);
            message.setReplyTo(new Address[] { smtpFromAddress });
        } else {
            handleException("From address for outgoing message cannot be determined");
        }
    }

    // set To address/es to any custom transport header set on the message, else use the reply
    // address from the out transport information
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) {
        Address[] to = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO));
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(to) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.TO, to);
    } else if (outInfo.getTargetAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting To header to " + InternetAddress.toString(outInfo.getTargetAddresses())
                    + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses());
    } else {
        handleException("To address for outgoing message cannot be determined");
    }

    // set Cc address/es to any custom transport header set on the message, else use the
    // Cc list from original request message
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) {
        Address[] cc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC));
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(cc) + " from transport headers");
        }
        message.setRecipients(Message.RecipientType.CC, cc);
    } else if (outInfo.getCcAddresses() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Cc header to " + InternetAddress.toString(outInfo.getCcAddresses())
                    + " from OutTransportInfo");
        }
        message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses());
    }

    // set Bcc address/es to any custom addresses set at the transport sender level + any
    // custom transport header
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) {
        InternetAddress[] bcc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC));
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(bcc) + " from transport headers");
        }
        message.addRecipients(Message.RecipientType.BCC, bcc);
    }
    if (smtpBccAddresses != null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding Bcc header values " + InternetAddress.toString(smtpBccAddresses)
                    + " from transport configuration");
        }
        message.addRecipients(Message.RecipientType.BCC, smtpBccAddresses);
    }

    // set subject
    if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)
                    + "' from transport headers");
        }
        message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT));
    } else if (outInfo.getSubject() != null) {
        if (log.isDebugEnabled()) {
            log.debug("Setting Subject header to '" + outInfo.getSubject() + "' from transport headers");
        }
        message.setSubject(outInfo.getSubject());
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Generating default Subject header from SOAP action");
        }
        message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction());
    }

    //TODO: use a combined message id for smtp so that it generates a unique id while
    // being able to support asynchronous communication.
    // if a custom message id is set, use it
    //        if (msgContext.getMessageID() != null) {
    //            message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID());
    //            message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID());
    //        }

    // if this is a reply, set reference to original message
    if (outInfo.getRequestMessageID() != null) {
        message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID());
        message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID());

    } else {
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) {
            message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO));
        }
        if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) {
            message.setHeader(MailConstants.MAIL_HEADER_REFERENCES,
                    (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES));
        }
    }

    // set Date
    message.setSentDate(new Date());

    // set SOAPAction header
    message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());

    // write body
    MessageFormatterEx messageFormatterEx;
    if (messageFormatter instanceof MessageFormatterEx) {
        messageFormatterEx = (MessageFormatterEx) messageFormatter;
    } else {
        messageFormatterEx = new MessageFormatterExAdapter(messageFormatter);
    }

    DataHandler dataHandler = new DataHandler(
            messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction()));

    MimeMultipart mimeMultiPart = null;

    String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT);
    if (mFormat == null) {
        mFormat = defaultMailFormat;
    }

    if (log.isDebugEnabled()) {
        log.debug("Using mail format '" + mFormat + "'");
    }

    MimePart mainPart;
    if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);
        mainPart = mimeBodyPart2;
    } else if (MailConstants.TRANSPORT_FORMAT_ATTACHMENT.equals(mFormat)) {
        mimeMultiPart = new MimeMultipart();
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent("Web Service Message Attached", "text/plain");
        MimeBodyPart mimeBodyPart2 = new MimeBodyPart();
        mimeMultiPart.addBodyPart(mimeBodyPart1);
        mimeMultiPart.addBodyPart(mimeBodyPart2);
        message.setContent(mimeMultiPart);

        String fileName = (String) msgContext.getProperty(MailConstants.TRANSPORT_FORMAT_ATTACHMENT_FILE);
        if (fileName != null) {
            mimeBodyPart2.setFileName(fileName);
        } else {
            mimeBodyPart2.setFileName("attachment");
        }

        mainPart = mimeBodyPart2;
    } else {
        mainPart = message;
    }

    try {
        mainPart.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction());
        mainPart.setDataHandler(dataHandler);

        // AXIOM's idea of what is textual also includes application/xml and
        // application/soap+xml (which JavaMail considers as binary). For these content types
        // always use quoted-printable transfer encoding. Note that JavaMail is a bit smarter
        // here because it can choose between 7bit and quoted-printable automatically, but it
        // needs to scan the entire content to determine this.
        if (msgContext.getOptions().getProperty("Content-Transfer-Encoding") != null) {
            mainPart.setHeader("Content-Transfer-Encoding",
                    (String) msgContext.getOptions().getProperty("Content-Transfer-Encoding"));
        } else {
            String contentType = dataHandler.getContentType().toLowerCase();
            if (!contentType.startsWith("multipart/") && CommonUtils.isTextualPart(contentType)) {
                mainPart.setHeader("Content-Transfer-Encoding", "quoted-printable");
            }
        }

        //setting any custom headers defined by the user
        if (msgContext.getOptions().getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS) != null) {
            Map customTransportHeaders = (Map) msgContext.getOptions()
                    .getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS);
            for (Object header : customTransportHeaders.keySet()) {
                mainPart.setHeader((String) header, (String) customTransportHeaders.get(header));
            }
        }

        log.debug("Sending message");
        Transport.send(message);

        // update metrics
        metrics.incrementMessagesSent(msgContext);
        long bytesSent = message.getBytesSent();
        if (bytesSent != -1) {
            metrics.incrementBytesSent(msgContext, bytesSent);
        }

    } catch (MessagingException e) {
        metrics.incrementFaultsSending();
        handleException("Error creating mail message or sending it to the configured server", e);

    }
    return message.getMessageID();
}

From source file:gov.nih.nci.cacisweb.util.CaCISUtil.java

/**
 * Sends email by setting some of the email properties that are common to Secure Email and XDS/NAV
 * //from  w  w w  . j  a  v a  2 s .  c o m
 * @param host
 * @param port
 * @param protocol
 * @param senderEmail
 * @param senderUser
 * @param senderPassword
 * @param subject
 * @param message
 * @param recepientEmail
 * @throws EmailException
 */
public void sendEmail(String host, String port, String senderEmail, String senderUser, String senderPassword,
        String subject, String body, String recepientEmail) throws MessagingException {
    log.debug("sendEmail(String host, String port, String protocol, String senderEmail, String senderUser,"
            + "String senderPassword, String subject, String message, String recepientEmail) - start");

    final String username = senderUser;
    final String password = senderPassword;

    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", port);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(senderEmail));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recepientEmail));
    message.setSubject(subject);
    message.setText(body);

    Transport.send(message);

    System.out.println("Done");

    // Email email = new SimpleEmail();
    // email.setHostName(host);
    // email.setSmtpPort(port);
    // // email.setAuthentication(senderUser, senderPassword);
    // email.setAuthenticator(new DefaultAuthenticator(senderUser, senderPassword));
    // email.addTo(recepientEmail);
    // email.setFrom(senderEmail);
    // email.setSubject(subject);
    // email.setMsg(message);
    // //email.setSSL(true);
    // log.info(String.format("Sending Email to %s, to report successful setup.", recepientEmail));
    // email.send();

    log.debug("sendEmail(String host, String port, String protocol, String senderEmail, String senderUser,"
            + "String senderPassword, String subject, String message, String recepientEmail) - end");
}

From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java

/**
 * This is the actual java mail execution.
 *
 * @param notification/*from w ww  .  j a v a2s.co m*/
 */
private void send(EmailTemplate notification) {

    String from = notification.getFrom();
    String to = notification.getTo();
    String subject = notification.getSubject();
    String style = notification.getStyle();

    // body of the email is set and all substitutions of variables are made
    String body = notification.getBody();

    // Get system properties
    Properties props = System.getProperties();

    // Setup mail server

    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtps.port", smtpPort);
    props.put("mail.smtps.auth", smtpUseAuth ? "true" : "false");

    // if (smtpUseAuth) {
    //
    // props.setProperty("mail.smtp.auth", smtpUseAuth + "");
    // props.setProperty("mail.username", smtpUsername);
    // props.setProperty("mail.password", smtpPassword);
    //
    // }

    // Get the default Session object.
    Session session = Session.getDefaultInstance(props);

    // Create a default MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    try {
        // Set the RFC 822 "From" header field using the
        // value of the InternetAddress.getLocalAddress method.
        message.setFrom(new InternetAddress(from));
        // Add the given addresses to the specified recipient type.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set the "Subject" header field.
        message.setSubject(subject);

        // Sets the given String as this part's content,
        // with a MIME type of "text/html".
        message.setContent(style + body, "text/html");

        if (smtpUseAuth) {
            // Send message
            Transport tr = session.getTransport(smtpProtocol);
            tr.connect(smtpHost, smtpPort, smtpUsername, smtpPassword);

            message.saveChanges();
            tr.sendMessage(message, message.getAllRecipients());
            tr.close();
        } else {
            Transport.send(message);
        }
    } catch (AddressException e) {
        log.error("Email Exception: Cannot connect to email host: " + smtpHost, e);
    } catch (MessagingException e) {
        log.error("Email Exception: Cannot send email message", e);
    }

}

From source file:Implement.Service.AdminServiceImpl.java

@Override
public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException {
    String path = System.getProperty("catalina.base");
    MimeBodyPart logo = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png"));
    logo.setDataHandler(new DataHandler(source));
    logo.setFileName("logoIcon.png");
    logo.setDisposition(MimeBodyPart.INLINE);
    logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid

    MimeBodyPart facebook = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png"));
    facebook.setDataHandler(new DataHandler(source));
    facebook.setFileName("facebookIcon.png");
    facebook.setDisposition(MimeBodyPart.INLINE);
    facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid

    MimeBodyPart twitter = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png"));
    twitter.setDataHandler(new DataHandler(source));
    twitter.setFileName("twitterIcon.png");
    twitter.setDisposition(MimeBodyPart.INLINE);
    twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid

    MimeBodyPart insta = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png"));
    insta.setDataHandler(new DataHandler(source));
    insta.setFileName("instaIcon.png");
    insta.setDisposition(MimeBodyPart.INLINE);
    insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid

    MimeBodyPart youtube = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png"));
    youtube.setDataHandler(new DataHandler(source));
    youtube.setFileName("youtubeIcon.png");
    youtube.setDisposition(MimeBodyPart.INLINE);
    youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid

    MimeBodyPart pinterest = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png"));
    pinterest.setDataHandler(new DataHandler(source));
    pinterest.setFileName("pinterestIcon.png");
    pinterest.setDisposition(MimeBodyPart.INLINE);
    pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid

    String content = "<div style=' width: 507px;background-color: #f2f2f4;'>"
            + "    <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>"
            + "        <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>"
            + "        <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + "    </div>"
            + "    <div style=' padding: 50px;margin-bottom: 20px;'>" + "        <div id='email-form'>"
            + "            <div style='margin-bottom: 20px'>" + "                Hi " + emailData.getLastName()
            + " ,<br/>" + "                Your package " + emailData.getLastestPackageName()
            + " has been approved" + "            </div>" + "            <div style='margin-bottom: 20px'>"
            + "                Thanks,<br/>" + "                Youtripper team\n" + "            </div>"
            + "        </div>" + "        <div style='border-top: solid 1px #c4c5cc;text-align:center;'>"
            + "            <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>"
            + "            <div>"
            + "                <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>"
            + "                <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>"
            + "                <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>"
            + "                <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>"
            + "                <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>"
            + "            </div>"
            + "            <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon,"
            + "                <br>Pravet, Bangkok, Thailand 10250</p>" + "        </div>" + "    </div>"
            + "</div>";

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);/*from   ww  w  .j  ava2s .  c om*/
    mp.addBodyPart(logo);
    mp.addBodyPart(facebook);
    mp.addBodyPart(twitter);
    mp.addBodyPart(insta);
    mp.addBodyPart(youtube);
    mp.addBodyPart(pinterest);

    final String username = "noreply@youtripper.com";
    final String password = "Tripper190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("noreply@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail()));
    message.setSubject("Package Approved!");
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);
    return true;
}

From source file:com.quartz.AmazonQuartzJob.java

public void execute(JobExecutionContext context) throws JobExecutionException {
    String error = "No error";
    SimpleDateFormat out = new SimpleDateFormat("hh:mm a");
    System.out.println(":::>>>Amazon Job Time Check @ " + out.format(new Date()));

    settingsHM = TextFileReadWrite.readSettings(file);

    String onoff = settingsHM.get("onoff"), emails = settingsHM.get("emails"),
            lastUpdate = settingsHM.get("lastUpdate");
    ArrayList<String> time = new ArrayList(Arrays.asList(settingsHM.get("time").split(";")));

    if (emails == null) {
        emails = ";";
    }//w ww .jav  a  2 s  .com
    Date lastDate;
    try {
        lastDate = out1.parse(lastUpdate);
    } catch (ParseException ex) {
        GregorianCalendar now = new GregorianCalendar();
        now.set(Calendar.DAY_OF_YEAR, -1);
        lastDate = now.getTime();
    }

    String[] emailArr = emails.replace(";;", ";").replace(";", " ").trim().split(" ");
    if (onoff.equalsIgnoreCase("checked")) {
        for (String e : time) {
            Date dScheduled, dNow;
            try {
                dScheduled = out.parse(e);
                dNow = out.parse(out.format(new Date()));
                if (dScheduled.getTime() == dNow.getTime()) {
                    System.out.println("\t---> Amazon task launch");

                    XMLOrderConfirmationFeedBuilder.generateShipConfirmXML();

                    try {
                        this.submitFeed();
                    } catch (IOException ex) {
                        System.out.println("Error occured in submitFeed method");
                        error += "Cannot submit feed.";
                    }

                    try {
                        if (emails != null && emails.length() > 0) {
                            for (String recipient : emailArr) {
                                InternetAddress.parse(recipient);
                                if (recipient.indexOf("@") > 0 && recipient.indexOf(".") > 0) {
                                    String subject = "Auto notification from AMZ order update application server";
                                    String msg = "Scheduled Amazon orders update executed.\nError/s: " + error
                                            + "\n\n Update contents:\n\n"
                                            + XML.toJSONObject(TextFileReadWrite
                                                    .readFile(new File("AMZ_Orders_Tracking_Feed.xml"))[0])
                                                    .toString(3);
                                    Emailer.Send(AKC_Creds.ANH_EMAIL, AKC_Creds.ANH_EMAIL_PWD, recipient,
                                            subject, msg);
                                }
                            }
                        }
                        System.out.println("===[email notifications send]===");
                        writeUpdateTimestamp();
                    } catch (MessagingException ex) {
                        System.out.println(ex.getMessage());
                    }

                } else {
                    //System.out.println("\txxx> AMZ task time not match | Scheduled: " + out.format(dScheduled) + " Now: " + out.format(dNow));
                }
            } catch (ParseException ex) {
                //System.out.println(ex.getMessage());
                error += " Cannot create XML feed.";
            }
        }
    }

}