Example usage for javax.mail Message saveChanges

List of usage examples for javax.mail Message saveChanges

Introduction

In this page you can find the example usage for javax.mail Message saveChanges.

Prototype

public abstract void saveChanges() throws MessagingException;

Source Link

Document

Save any changes made to this message into the message-store when the containing folder is closed, if the message is contained in a folder.

Usage

From source file:com.trivago.mail.pigeon.mail.MailFacade.java

public void readBounceAccount() throws MessagingException {
    Session session = Session.getDefaultInstance(Settings.create().getConfiguration().getProperties("mail.*"));
    Store store = session.getStore("pop3");

    store.connect();//from   ww  w. j av a 2  s. c  o  m

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);

    if (folder.hasNewMessages()) {
        // Get directory
        Message message[] = folder.getMessages();
        BounceFacade bounceFacade = new BounceFacade();

        for (Message msg : message) {
            boolean isBounce = bounceFacade.processBounce(msg);
            if (isBounce) {
                msg.setFlag(Flags.Flag.SEEN, true);
                msg.saveChanges();
            }
        }
    }

}

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

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

    }
}

From source file:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;//w w  w.j  av a 2  s  . c o m

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents 
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        System.out.println("Sending failed with exception:");
        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++)
                        System.out.println("         " + invalid[i]);
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++)
                        System.out.println("         " + validUnsent[i]);
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++)
                        System.out.println("         " + validSent[i]);
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            if (trans != null)
                trans.close();
        } catch (MessagingException mex) {
            /* ignore */ }
    }
}

From source file:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/*from  ww  w. j a va2 s  .  c om*/

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++)
                            System.out.println("         " + invalid[i]);
                    }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            System.out.println("         " + validUnsent[i]);
                    }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++)
                            System.out.println("         " + validSent[i]);
                    }
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            trans.close();
        } catch (MessagingException mex) { /* ignore */
        }
    }
}

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  w w  w.ja  v  a2s. c  o  m
    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.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java

protected void sendEmail(EmailConfiguration config, String recipientAddress, String subject, String body) {
    String mailHost = config.getMailServer();
    Boolean mailUseSMTPS = config.isSMTPS();
    String mailUser = config.getUsername();
    String mailPassword = config.getPassword();

    if (mailHost == null) {
        throw new HobsonRuntimeException("No mail host is configured; unable to execute e-mail action");
    } else if (mailUseSMTPS && mailUser == null) {
        throw new HobsonRuntimeException(
                "No mail server username is configured for SMTPS; unable to execute e-mail action");
    } else if (mailUseSMTPS && mailPassword == null) {
        throw new HobsonRuntimeException(
                "No mail server password is configured for SMTPS; unable to execute e-mail action");
    }//from w ww  .  j  a va2  s.c  om

    // create mail session
    Properties props = new Properties();
    props.put("mail.smtp.host", mailHost);
    Session session = Session.getDefaultInstance(props, null);

    // create the mail message
    Message msg = createMessage(session, config, recipientAddress, subject, body);

    // send the message
    String protocol = mailUseSMTPS ? "smtps" : "smtp";
    int port = mailUseSMTPS ? 465 : 25;
    try {
        Transport transport = session.getTransport(protocol);
        logger.debug("Sending e-mail to {} using {}@{}:{}", msg.getAllRecipients(), mailUser, mailHost, port);
        transport.connect(mailHost, port, mailUser, mailPassword);
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        logger.debug("Message sent successfully");
    } catch (MessagingException e) {
        logger.error("Error sending e-mail message", e);
        throw new HobsonRuntimeException("Error sending e-mail message", e);
    }
}

From source file:mail.MailService.java

/**
 * Erstellt eine MIME-Mail.//from   w  ww.j ava  2  s . c  o m
 * @param email
 * @throws MessagingException
 * @throws IOException
 */
public String createMail1(Mail email, Config config) throws MessagingException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    Message msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());
    String txt = Utils.toString(email.getText());

    msg.setText(txt);
    msg.saveChanges();

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        if (config.isTest())
            System.out.println("Fehler beim Schreiben der Mail in Schritt 1");
        throw e;
    }
    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}

From source file:mail.MailService.java

/**
 * Erstellt eine kanonisierte MIME-Mail.
 * @param email/* ww w  .  j a  v a2 s  .co  m*/
 * @throws MessagingException
 * @throws IOException
 */
public String createMail2(Mail email, Config config) throws MessagingException, IOException {

    byte[] mailAsBytes = email.getText();
    int laenge = mailAsBytes.length + getCRLF().length;
    byte[] bOout = new byte[laenge];
    for (int i = 0; i < mailAsBytes.length; i++) {
        bOout[i] = mailAsBytes[i];
    }

    byte[] neu = getCRLF();
    int counter = 0;
    for (int i = mailAsBytes.length; i < laenge; i++) {
        bOout[i] = neu[counter];
        counter++;
    }

    email.setText(bOout);

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    Message msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());

    msg.setText(Utils.toString(email.getText()));
    msg.saveChanges();
    /*       
           // Erstellen des Content
           MimeMultipart content = new MimeMultipart("text"); 
                  
           MimeBodyPart part = new MimeBodyPart(); 
           part.setText(email.getText()); 
           part.setHeader("MIME-Version" , "1.0"); 
           part.setHeader("Content-Type" , part.getContentType()); 
                   
           content.addBodyPart(part);
           System.out.println(content.getContentType());
                  
          Message msg = new MimeMessage(session); 
          msg.setContent(content); 
          msg.setHeader("MIME-Version" , "1.0"); 
          msg.setHeader("Content-Type" , content.getContentType()); 
            
          InternetAddress addressFrom = new InternetAddress(email.getAbsender()); 
           msg.setFrom(addressFrom); 
                   
           InternetAddress addressTo = new InternetAddress(email.getEmpfnger()); 
           msg.setRecipient(Message.RecipientType.TO, addressTo); 
                   
           msg.setSubject(email.getBetreff());
           msg.setSentDate(email.getAbsendeDatum()); */

    //msg.setContent(email.getText(), "text/plain");

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        System.out.println("Fehler beim Schreiben der Mail in Schritt 2");
        throw e;
    }
    //      String out = bOut.toString();
    //       int pos1 = out.indexOf("Message-ID");
    //       int pos2 = out.indexOf("@localhost") + 13;
    //       String output = out.subSequence(0, pos1).toString();
    //       output += (out.substring(pos2));

    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}

From source file:com.tremolosecurity.proxy.auth.PasswordReset.java

private void sendEmail(SmtpMessage msg) throws MessagingException {
    Properties props = new Properties();

    props.setProperty("mail.smtp.host", this.reset.getSmtpServer());
    props.setProperty("mail.smtp.port", Integer.toString(reset.getSmtpPort()));
    props.setProperty("mail.smtp.user", reset.getSmtpUser());
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.starttls.enable", Boolean.toString(reset.isSmtpTLS()));
    //props.setProperty("mail.debug", "true");
    //props.setProperty("mail.socket.debug", "true");

    if (reset.getSmtpLocalhost() != null && !reset.getSmtpLocalhost().isEmpty()) {
        props.setProperty("mail.smtp.localhost", reset.getSmtpLocalhost());
    }//www. j av a 2  s . c o  m

    if (reset.isUseSocks()) {

        props.setProperty("mail.smtp.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtp.socks.port", Integer.toString(reset.getSocksPort()));
        props.setProperty("mail.smtps.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtps.socks.port", Integer.toString(reset.getSocksPort()));
    }

    //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword));
    Session session = Session.getDefaultInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(reset.getSmtpUser(), reset.getSmtpPassword());
        }
    });
    //Session session = Session.getInstance(props, null);
    session.setDebugOut(System.out);
    //session.setDebug(true);
    //Transport tr = session.getTransport("smtp");
    //tr.connect();

    //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword);

    Message msgToSend = new MimeMessage(session);
    msgToSend.setFrom(new InternetAddress(msg.from));
    msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to));
    msgToSend.setSubject(msg.subject);
    msgToSend.setText(msg.msg);

    msgToSend.saveChanges();
    Transport.send(msgToSend);
    //tr.sendMessage(msg, msg.getAllRecipients());
    //tr.close();
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * Create a reply message to the given message. The reply message is
 * addressed to only the from / reply address or all receipients based on
 * the replyToAll flag.//from  w w  w  .java 2 s  . c o  m
 *
 * @param fromName DOCUMENT ME!
 * @param fromEmail DOCUMENT ME!
 * @param message The message which to reply
 * @param body The attached text to include in the reply
 * @param replyToAll Reply to all receipients of the original message
 *
 * @return Message Reply message
 *
 * @exception MessagingException if the message contents are invalid
 */
public static Message createReply(Address[] from, Message message, boolean replyToAll)
        throws MessagingException {
    if ((from == null) || (from.length <= 0)) {
        throw new MessagingException("The from is null");
    }

    // create an empty reply message
    Message xreply = message.reply(replyToAll);

    // set the default from address
    xreply.setFrom(from[0]);

    // Message.reply() may set the "replied to" flag, so
    // attempt to save that new state and fail silently...
    try {
        message.saveChanges();
    } catch (MessagingException ex) {
    }

    return xreply;
}