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:contestWebsite.ContactUs.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query("user")
            .setFilter(new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("name")));
    List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(3));
    Entity feedback = new Entity("feedback");
    if (users.size() != 0) {
        feedback.setProperty("user-id", users.get(0).getProperty("user-id"));
    }/*from w ww  . jav  a  2s.c o  m*/

    String name = escapeHtml4(req.getParameter("name"));
    String school = escapeHtml4(req.getParameter("school"));
    String comment = escapeHtml4(req.getParameter("text"));
    String email = escapeHtml4(req.getParameter("email"));

    HttpSession sess = req.getSession(true);
    sess.setAttribute("name", name);
    sess.setAttribute("school", school);
    sess.setAttribute("email", email);
    sess.setAttribute("comment", comment);

    Entity contestInfo = Retrieve.contestInfo();
    if (!(Boolean) sess.getAttribute("nocaptcha")) {
        URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify");
        String charset = java.nio.charset.StandardCharsets.UTF_8.name();
        String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset),
                URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset),
                URLEncoder.encode(req.getRemoteAddr(), charset));

        final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return connection.getInputStream();
            }
        }, Charsets.UTF_8));

        try {
            JSONObject JSONResponse = new JSONObject(response);
            if (!JSONResponse.getBoolean("success")) {
                resp.sendRedirect("/contactUs?captchaError=1");
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendRedirect("/contactUs?captchaError=1");
            return;
        }
    }

    feedback.setProperty("name", name);
    feedback.setProperty("school", school);
    feedback.setProperty("email", email);
    feedback.setProperty("comment", new Text(comment));
    feedback.setProperty("resolved", false);

    Transaction txn = datastore.beginTransaction();
    try {
        datastore.put(feedback);
        txn.commit();

        Session session = Session.getDefaultInstance(new Properties(), null);
        String appEngineEmail = (String) contestInfo.getProperty("account");

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress((String) contestInfo.getProperty("email"), "Contest Administrator"));
            msg.setSubject("Question about tournament from " + name);
            msg.setReplyTo(new InternetAddress[] { new InternetAddress(req.getParameter("email"), name),
                    new InternetAddress(appEngineEmail, "Tournament Website Admin") });

            VelocityEngine ve = new VelocityEngine();
            ve.init();

            VelocityContext context = new VelocityContext();
            context.put("name", name);
            context.put("email", email);
            context.put("school", school);
            context.put("message", comment);

            StringWriter sw = new StringWriter();
            Velocity.evaluate(context, sw, "questionEmail",
                    ((Text) contestInfo.getProperty("questionEmail")).getValue());
            msg.setContent(sw.toString(), "text/html");
            Transport.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        resp.sendRedirect("/contactUs?updated=1");
        sess.invalidate();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}

From source file:populate.java

/**
 * Copy message from src to dst. If dontPreserveFlags is set we first copy the
 * messages to memory, clear all the flags, and then copy to the destination.
 *//*from   ww  w .jav  a 2 s .c om*/
private static void copyMessages(Folder src, Folder dst) throws MessagingException {
    Message[] msgs = src.getMessages();
    if (dontPreserveFlags) {
        for (int i = 0; i < msgs.length; i++) {
            MimeMessage m = new MimeMessage((MimeMessage) msgs[i]);
            m.setFlags(m.getFlags(), false);
            msgs[i] = m;
        }
    }
    src.copyMessages(msgs, dst);
}

From source file:com.silverpeas.mailinglist.service.notification.AdvancedNotificationHelperTest.java

@Test
public void testMultiSendMail() throws Exception {
    MimeMessage mail = new MimeMessage(notificationHelper.getSession());
    InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com");
    mail.addFrom(new InternetAddress[] { theSimpsons });
    mail.setSubject("Simple text Email test");
    mail.setText(textEmailContent);//from w w  w.j  a va  2s .  com
    List<ExternalUser> externalUsers = new LinkedList<ExternalUser>();
    ExternalUser user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("bart.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("homer.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("lisa.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("marge.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("maggie.simpson@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("ned.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("maude.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("rod.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("todd.flanders@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("krusty.theklown@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("selma.bouvier@silverpeas.com");
    externalUsers.add(user);
    user = new ExternalUser();
    user.setComponentId("100");
    user.setEmail("patty.bouvier@silverpeas.com");
    externalUsers.add(user);
    assertThat(externalUsers.size(), is(12));
    notificationHelper.sendMail(mail, externalUsers);
    Iterator<ExternalUser> iter = externalUsers.iterator();
    while (iter.hasNext()) {
        ExternalUser recipient = iter.next();
        checkSimpleEmail(recipient.getEmail(), "Simple text Email test");
    }
}

From source file:mitm.application.djigzo.james.mailets.RequestSenderCertificateTest.java

@Test
public void testRequestCertificateOverrideCertificateRequestHandler() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig();

    RequestSenderCertificate mailet = new RequestSenderCertificate();

    // specify an unknown request handler so we can check the queue
    mailetConfig.setInitParameter("certificateRequestHandler", "unknown");

    mailet.init(mailetConfig);/*from w  ww.  java2 s .c o  m*/

    MockMail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("from@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("to@example.com"));

    mail.setRecipients(recipients);

    mail.setSender(new MailAddress("somethingelse@example.com"));

    mailet.service(mail);

    assertEquals(0, proxy.getCertificateRequestStoreSize());
    assertEquals(INITIAL_KEY_STORE_SIZE, proxy.getKeyAndCertStoreSize());
}

From source file:app.logica.gestores.GestorEmail.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to/* w ww. ja  v a  2s . c o  m*/
 *            Email address of the receiver.
 * @param from
 *            Email address of the sender, the mailbox account.
 * @param subject
 *            Subject of the email.
 * @param bodyText
 *            Body text of the email.
 * @param file
 *            Path to the file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
private MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        File file) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(file);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(file.getName());

    multipart.addBodyPart(mimeBodyPart);
    email.setContent(multipart);

    return email;
}

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testNegativeValidityInterval() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/*www  .ja v a2 s .  c  o m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test7@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(1, result.size());
}

From source file:com.quinsoft.zeidon.zeidonoperations.ZDRVROPR.java

public int CreateSeeMessage(int lConnection, String szSMTPServer, String szUserEmailAddress,
        String szRecipientEmailAddress, String szCCAddress, String szBCCAddress, String szSubjectText,
        int MimeType, String szMessageBody, String string4, String string5, int attachmentFlag,
        String szAttachmentFileName, String szUserEmailName, String szUserEmailPassword) {
    InternetAddress fromAddress = null;//from  w  ww. jav  a 2s . c  om
    String host = szSMTPServer; //enc-exhub.enc-ad.enc.edu
    String from = szUserEmailAddress;
    String to[] = szRecipientEmailAddress.split("[\\s,;]+");
    InternetAddress[] toAddress = new InternetAddress[to.length];
    String cc[] = szCCAddress.split("[\\s,;]+");
    InternetAddress[] ccAddress = new InternetAddress[cc.length];
    String bcc[] = szBCCAddress.split("[\\s,;]+");
    InternetAddress[] bccAddress = new InternetAddress[bcc.length];
    //String host = "enc-exhub.enc-ad.enc.edu";
    //String from = "kellysautter@comcast.net";
    //String to = "kellysautter@comcast.net";

    // Set properties
    Properties props = new Properties();
    //mail.smtp.sendpartial
    props.put("mail.smtp.host", host);
    props.put("mail.debug", "true");

    // Get session
    // Going to use getDefaultInstance
    // If I get java.lang.SecurityException: Access to default session denied
    // then it said to go use .getInstance(props).
    Session session = Session.getDefaultInstance(props);

    try {
        // Instantiate a message
        Message msg = new MimeMessage(session);

        try {
            if (from != null && !from.isEmpty())
                fromAddress = new InternetAddress(from);
            if (szRecipientEmailAddress != null && !szRecipientEmailAddress.isEmpty()) {
                for (int iCnt = 0; iCnt < to.length; iCnt++) {
                    toAddress[iCnt] = new InternetAddress(to[iCnt]);
                }
            }
            if (szCCAddress != null && !szCCAddress.isEmpty()) {
                for (int iCnt = 0; iCnt < cc.length; iCnt++) {
                    ccAddress[iCnt] = new InternetAddress(cc[iCnt]);
                }
            }
            if (szBCCAddress != null && !szBCCAddress.isEmpty()) {
                for (int iCnt = 0; iCnt < bcc.length; iCnt++) {
                    bccAddress[iCnt] = new InternetAddress(bcc[iCnt]);
                }
            }
        } catch (AddressException e) {
            task.log().error("*** CreateSeeMessage: setting addresses **** ");
            task.log().error(e);
            return -1;
        }
        // Set the FROM message
        msg.setFrom(fromAddress);

        if (szRecipientEmailAddress != null && !szRecipientEmailAddress.isEmpty())
            msg.setRecipients(Message.RecipientType.TO, toAddress);
        if (szCCAddress != null && !szCCAddress.isEmpty())
            msg.setRecipients(Message.RecipientType.CC, ccAddress);
        if (szBCCAddress != null && !szBCCAddress.isEmpty())
            msg.setRecipients(Message.RecipientType.BCC, bccAddress);

        // Set the message subject and date we sent it.
        msg.setSubject(szSubjectText);
        msg.setSentDate(new Date());

        // Set message content
        msg.setText(szMessageBody);

        // Send the message
        Transport.send(msg);
    } catch (MessagingException mex) {
        task.log().error("*** CreateSeeMessage: Transport.send error ****  ");
        task.log().error(mex);
        // Email was bad?
        if (mex instanceof SendFailedException)
            return -1;

        // SMTP connection bad?
        return -2;
    }

    return 0;
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*w w  w.j  a v a 2 s . c  o  m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static ErrorType sendMsg(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, final String port, final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;

    if (StringUtils.isEmpty(toEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR");
        return ErrorType.Error;
    }

    if (StringUtils.isEmpty(fromEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR");
        return ErrorType.Error;
    }

    //if (isGmailEmail())
    //{
    //    return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment);
    //}

    Boolean fail = false;
    ArrayList<String> userAndPass = new ArrayList<String>();

    boolean isSSL = security.equals("SSL");

    String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable",
            "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback",
            "mail.imap.auth.plain.disable", };
    Properties props = System.getProperties();
    for (String key : keys) {
        props.remove(key);
    }

    props.put("mail.smtp.host", host); //$NON-NLS-1$

    if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) {
        props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        props.remove("mail.smtp.port");
    }

    if (StringUtils.isNotEmpty(security)) {
        if (security.equals("TLS")) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

        } else if (isSSL) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$

            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.imap.auth.plain.disable", "true");
        }
    }

    Session session = null;
    if (isSSL) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uName, pWord);
            }
        });

    } else {
        session = Session.getInstance(props, null);
    }

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
        log.debug("Port:     " + port); //$NON-NLS-1$
        log.debug("Security: " + security); //$NON-NLS-1$
    }

    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));

        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            try {
                InternetAddress[] address = { new InternetAddress(toEMailAddr) };
                msg.setRecipients(Message.RecipientType.TO, address);

            } catch (javax.mail.internet.AddressException ex) {
                UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr);
                return ErrorType.Error;
            }
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

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

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        final int TRIES = 1;

        // set the Date: header
        msg.setSentDate(new Date());

        Exception exception = null;
        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                if (isSSL) {
                    Transport.send(msg);

                } else {
                    t.connect(host, userName, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                }

                fail = false;

            } catch (SendFailedException mex) {
                mex.printStackTrace();
                exception = mex;

            } catch (MessagingException mex) {
                if (mex.getCause() instanceof UnknownHostException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host);

                } else if (mex.getCause() instanceof ConnectException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError(
                            "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port);

                } else {
                    mex.printStackTrace();
                    exception = mex;
                }

            } catch (Exception mex) {
                mex.printStackTrace();
                exception = mex;

            } finally {
                if (t != null) {
                    log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                    t.close();
                }
            }

            if (exception != null) {
                fail = true;

                instance.lastErrorMsg = exception.toString();

                //wrong username or password, get new one
                if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName);

                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) { //the user is done
                        instance.lastErrorMsg = null;
                        return ErrorType.Cancel;
                    }
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }

            }
            exception = null;

        } while (fail && cnt < TRIES);

    } catch (Exception mex) {
        //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        mex.printStackTrace();
        Exception ex = null;
        if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return ErrorType.Error;

    }

    if (fail) {
        return ErrorType.Error;
    } //else

    return ErrorType.OK;
}

From source file:com.appeligo.search.messenger.Messenger.java

/**
 * //from   w w  w . j  a v a 2  s . co m
 * @param messages
 */
public int send(com.appeligo.search.entity.Message... messages) {
    int sent = 0;
    if (messages == null) {
        return 0;
    }
    for (com.appeligo.search.entity.Message message : messages) {
        User user = message.getUser();
        if (user != null) {
            boolean changed = false;
            boolean abort = false;
            if ((!user.isEnabled()) || (!user.isRegistrationComplete())
                    || (message.isSms() && (!user.isSmsValid()))) {
                abort = true;
                if (message.getExpires() == null) {
                    Calendar cal = Calendar.getInstance();
                    cal.add(Calendar.HOUR, 24);
                    message.setExpires(new Timestamp(cal.getTimeInMillis()));
                    changed = true;
                }
            }
            if (message.isSms() && user.isSmsValid() && (!user.isSmsOKNow())) {

                Calendar now = Calendar.getInstance(user.getTimeZone());
                now.set(Calendar.MILLISECOND, 0);
                now.set(Calendar.SECOND, 0);

                Calendar nextWindow = Calendar.getInstance(user.getTimeZone());
                nextWindow.setTime(user.getEarliestSmsTime());
                nextWindow.set(Calendar.MILLISECOND, 0);
                nextWindow.set(Calendar.SECOND, 0);
                nextWindow.add(Calendar.MINUTE, 1); // compensate for zeroing out millis, seconds

                nextWindow.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));

                int nowMinutes = (now.get(Calendar.HOUR) * 60) + now.get(Calendar.MINUTE);
                int nextMinutes = (nextWindow.get(Calendar.HOUR) * 60) + nextWindow.get(Calendar.MINUTE);
                if (nowMinutes > nextMinutes) {
                    nextWindow.add(Calendar.HOUR, 24);
                }
                message.setDeferUntil(new Timestamp(nextWindow.getTimeInMillis()));
                changed = true;
                abort = true;
            }
            if (changed) {
                message.save();
            }
            if (abort) {
                continue;
            }
        }
        String to = message.getTo();
        String from = message.getFrom();
        String subject = message.getSubject();
        String body = message.getBody();
        String contentType = message.getMimeType();
        try {

            Properties props = new Properties();

            //Specify the desired SMTP server
            props.put("mail.smtp.host", mailHost);
            props.put("mail.smtp.port", Integer.toString(port));
            // create a new Session object
            Session session = null;
            if (password != null) {
                props.put("mail.smtp.auth", "true");
                session = Session.getInstance(props, new SMTPAuthenticator(smtpUser, password));
            } else {
                session = Session.getInstance(props, null);
            }
            session.setDebug(debug);

            // create a new MimeMessage object (using the Session created above)
            Message mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipients(Message.RecipientType.TO,
                    new InternetAddress[] { new InternetAddress(to) });
            mimeMessage.setSubject(subject);
            mimeMessage.setContent(body.toString(), contentType);
            if (mailHost.trim().equals("")) {
                log.info("No Mail Host.  Would have sent:");
                log.info("From: " + from);
                log.info("To: " + to);
                log.info("Subject: " + subject);
                log.info(mimeMessage.getContent());
            } else {
                Transport.send(mimeMessage);
                sent++;
            }
            message.setSent(new Date());
        } catch (Throwable t) {
            message.failedAttempt();
            if (message.getAttempts() >= maxAttempts) {
                message.setExpires(new Timestamp(System.currentTimeMillis()));
            }
            log.error(t.getMessage(), t);
        }
    }
    return sent;
}

From source file:davmail.smtp.TestSmtp.java

public void testDotMessage() throws IOException, MessagingException, InterruptedException {
    String body = "First line\r\n.\r\nSecond line";
    MimeMessage mimeMessage = new MimeMessage((Session) null);
    mimeMessage.addHeader("to", Settings.getProperty("davmail.to"));
    mimeMessage.setSubject("Test subject");
    mimeMessage.setText(body);//from ww  w .j ava  2  s.c  om
    sendAndCheckMessage(mimeMessage);
}