Example usage for javax.mail.internet MimeMessage MimeMessage

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

Introduction

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

Prototype

public MimeMessage(MimeMessage source) throws MessagingException 

Source Link

Document

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

Usage

From source file:com.flexoodb.common.FlexUtils.java

static public boolean sendMail(String host, int port, String from, String to, String subject, String msg)
        throws Exception {
    SMTPTransport transport = null;// w ww .  j  ava2s  .com
    boolean ok = false;
    try {
        InternetAddress[] rcptto = new InternetAddress[1];
        rcptto[0] = new InternetAddress(to);

        Properties props = System.getProperties();

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port + "");

        javax.mail.Session session = javax.mail.Session.getDefaultInstance(props, null);

        transport = (SMTPTransport) session.getTransport("smtp");

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setContent(msg, "text/html");
        //Transport.send(message);

        transport.setLocalHost("REMOTE-CLIENT");
        transport.connect();
        transport.sendMessage(message, rcptto);

        ok = true;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            transport.close();
        } catch (Exception f) {
            f.printStackTrace();
        }
    }
    return ok;
}

From source file:com.flexoodb.common.FlexUtils.java

static public String sendMailShowResult(String host, int port, String from, String to, String subject,
        String msg) throws Exception {
    String response = "OK";

    SMTPTransport transport = null;/*  w w w  . ja  v a 2s .c  o  m*/
    boolean ok = true;

    try {
        InternetAddress[] rcptto = new InternetAddress[1];
        rcptto[0] = new InternetAddress(to);

        Properties props = System.getProperties();

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port + "");
        props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original
        props.put("mail.smtp.timeout", "60000");
        props.put("mail.smtp.quitwait", "false");

        javax.mail.Session session = javax.mail.Session.getInstance(props);

        transport = (SMTPTransport) session.getTransport("smtp");

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setContent(msg, "text/html");
        //Transport.send(message);
        transport.setLocalHost("REMOTE-CLIENT");
        transport.connect();
        transport.sendMessage(message, rcptto);

    } catch (Exception e) {
        e.printStackTrace();
        ok = false;
    } finally {

        try {
            if (!ok) {
                response = "SENDING FAILED:" + transport.getLastServerResponse();
            } else {
                response = "SENDING SUCCESS:" + transport.getLastServerResponse();
            }

            transport.close();

        } catch (Exception f) {

        }

    }
    return response;
}

From source file:com.flexoodb.common.FlexUtils.java

static public String sendMailShowResult(String host, int port, String fromname, String from, String to,
        String subject, String msg) throws Exception {
    String response = "OK";

    SMTPTransport transport = null;//from w  w  w  . ja v  a2  s.  c o  m
    boolean ok = true;

    try {
        InternetAddress[] rcptto = new InternetAddress[1];
        rcptto[0] = new InternetAddress(to);

        Properties props = System.getProperties();

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port + "");
        props.put("mail.smtp.connectiontimeout", "60000"); // 300000 original
        props.put("mail.smtp.timeout", "60000");
        props.put("mail.smtp.quitwait", "false");

        javax.mail.Session session = javax.mail.Session.getInstance(props);

        transport = (SMTPTransport) session.getTransport("smtp");

        MimeMessage message = new MimeMessage(session);
        if (fromname == null || fromname.isEmpty()) {
            message.setFrom(new InternetAddress(from));
        } else {
            message.setFrom(new InternetAddress(from, fromname));
        }
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setContent(msg, "text/html");
        //Transport.send(message);
        transport.setLocalHost("REMOTE-CLIENT");
        transport.connect();
        transport.sendMessage(message, rcptto);

    } catch (Exception e) {
        e.printStackTrace();
        ok = false;
    } finally {

        try {
            if (!ok) {
                response = "SENDING FAILED:" + transport.getLastServerResponse();
            } else {
                response = "SENDING SUCCESS:" + transport.getLastServerResponse();
            }

            transport.close();

        } catch (Exception f) {

        }

    }
    return response;
}

From source file:it.infn.ct.wrf.Wrf.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String GATEWAY) {//from   w w  w.  ja va2 s.  co m

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- Gateway = " + GATEWAY);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

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

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

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

        // Set Subject: header field
        message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification"
                + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ "
                + ApplicationAcronym + " ]</b><br/><br/>"
                + "<i>The application has been successfully submitted from the [ " + GATEWAY
                + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>"
                + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>"
                + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:"
                + FROM + "\">contact us</a></i>", "text/html");

        // Send message
        Transport.send(message);
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

From source file:it.infn.ct.nuclemd.Nuclemd.java

private void sendHTMLEmail(String USERNAME, String TO, String FROM, String SMTP_HOST, String ApplicationAcronym,
        String GATEWAY) {//www  .ja va 2  s  .c o m

    log.info("\n- Sending email notification to the user " + USERNAME + " [ " + TO + " ]");

    log.info("\n- SMTP Server = " + SMTP_HOST);
    log.info("\n- Sender = " + FROM);
    log.info("\n- Receiver = " + TO);
    log.info("\n- Application = " + ApplicationAcronym);
    log.info("\n- Gateway = " + GATEWAY);

    // Assuming you are sending email from localhost
    String HOST = "localhost";

    // Get system properties
    Properties properties = System.getProperties();
    properties.setProperty(SMTP_HOST, HOST);

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

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

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(FROM));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        //message.addRecipient(Message.RecipientType.CC, new InternetAddress(FROM));

        // Set Subject: header field
        message.setSubject(" [liferay-sg-gateway] - [ " + GATEWAY + " ] ");

        Date currentDate = new Date();
        currentDate.setTime(currentDate.getTime());

        // Send the actual HTML message, as big as you like
        message.setContent("<br/><H4>"
                + "<img src=\"http://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/195775_220075701389624_155250493_n.jpg\" width=\"100\">Science Gateway Notification"
                + "</H4><hr><br/>" + "<b>Description:</b> Notification for the application <b>[ "
                + ApplicationAcronym + " ]</b><br/><br/>"
                + "<i>The application has been successfully submitted from the [ " + GATEWAY
                + " ]</i><br/><br/>" + "<b>TimeStamp:</b> " + currentDate + "<br/><br/>"
                + "<b>Disclaimer:</b><br/>"
                + "<i>This is an automatic message sent by the Science Gateway based on Liferay technology.<br/>"
                + "If you did not submit any jobs through the Science Gateway, please " + "<a href=\"mailto:"
                + FROM + "\">contact us</a></i>", "text/html");

        // Send message
        Transport.send(message);
    } catch (MessagingException ex) {
        Logger.getLogger(Nuclemd.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processCopyAttachment(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    try {//from  w  ww. j ava  2s .  com
        MailAccount fromaccount = getAccount(request.getParameter("fromaccount"));
        MailAccount toaccount = getAccount(request.getParameter("toaccount"));
        fromaccount.checkStoreConnected();
        toaccount.checkStoreConnected();
        UserProfile profile = environment.getProfile();
        Locale locale = profile.getLocale();

        String pfromfolder = request.getParameter("fromfolder");
        String ptofolder = request.getParameter("tofolder");
        String puidmessage = request.getParameter("idmessage");
        String pidattach = request.getParameter("idattach");

        FolderCache frommcache = fromaccount.getFolderCache(pfromfolder);
        FolderCache tomcache = toaccount.getFolderCache(ptofolder);
        long uidmessage = Long.parseLong(puidmessage);
        Message m = frommcache.getMessage(uidmessage);

        HTMLMailData mailData = frommcache.getMailData((MimeMessage) m);
        Object content = mailData.getAttachmentPart(Integer.parseInt(pidattach)).getContent();

        // We can copy attachments only if the content is an eml. If it is
        // explicit simply treat it as message, otherwise try to decode the
        // stream as a mime message. If an error is thrown during parse, it 
        // means that the stream is reconducible to a valid mime-message.
        MimeMessage msgContent = null;
        if (content instanceof MimeMessage) {
            msgContent = new MimeMessage((MimeMessage) content);
        } else if (content instanceof IMAPInputStream) {
            try {
                msgContent = new MimeMessage(fromaccount.getMailSession(), (IMAPInputStream) content);
            } catch (MessagingException ex1) {
                logger.debug("Stream cannot be interpreted as MimeMessage", ex1);
            }
        }

        if (msgContent != null) {
            msgContent.setFlag(Flags.Flag.SEEN, true);
            tomcache.appendMessage(msgContent);
            new JsonResult().printTo(out);
        } else {
            new JsonResult(false, lookupResource(locale, MailLocaleKey.ERROR_ATTACHMENT_TYPE_NOT_SUPPORTED))
                    .printTo(out);
        }

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        new JsonResult(false, exc.getMessage()).printTo(out);
    }
}

From source file:library.Form_Library.java

License:asdf

public void sendFromGMail(String from, String pass, String to, String subject, String body) {
    this.taBaoCao.append("Sent to " + to + " successfully.\n");
    Properties props = System.getProperties();
    String host = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {//from  w  w w  . j  av  a  2s  . c  o m
        message.setFrom(new InternetAddress(from));
        InternetAddress toAddress = new InternetAddress();

        // To get the array of addresses
        //            for( int i = 0; i < to.length; i++ ) {
        toAddress = new InternetAddress(to);
        //            }

        //            for( int i = 0; i < toAddress.length; i++) {
        message.addRecipient(Message.RecipientType.TO, toAddress);
        //            }

        message.setSubject(subject);
        message.setText(body);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);

        transport.sendMessage(message, message.getAllRecipients());

        System.out.print("Successfully Sent" + "\n");
        transport.close();
    } catch (AddressException ae) {
        ae.printStackTrace();
    } catch (MessagingException me) {
        me.printStackTrace();
    }
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public void send(WGAMailNotification notification) {
    WGAMailConfiguration config = getMailConfig();

    if (config != null && config.isEnableAdminNotifications()) {
        try {//from ww w . jav a2s. c  o  m
            Message msg = new MimeMessage(config.createMailSession());

            // set recipient and from address
            String toAddress = config.getToAddress();
            if (toAddress == null) {
                getLog().error(
                        "Unable to send wga admin notification because no recipient address is configured");
                return;
            }

            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            InternetAddress[] fromAddr = new InternetAddress[1];
            fromAddr[0] = new InternetAddress(config.getFromAddress());
            msg.addFrom(fromAddr);

            msg.setSentDate(new Date());

            InetAddress localMachine = InetAddress.getLocalHost();
            String hostname = localMachine.getHostName();
            String serverName = getWgaConfiguration().getServerName();
            if (serverName == null) {
                serverName = hostname;
            }

            msg.setSubject(notification.getSubject());

            msg.setHeader(WGAMailNotification.HEADERFIELD_TYPE, notification.getType());

            MimeMultipart content = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();

            StringBuffer strBody = new StringBuffer();
            strBody.append("<html><head></head><body style=\"color:#808080\">");
            strBody.append(notification.getMessage());
            String rootURL = getWgaConfiguration().getRootURL();
            if (rootURL != null) {
                //strBody.append("<br><br>");
                strBody.append("<p><a href=\"" + rootURL + "/plugin-admin\">" + WGABrand.getName()
                        + " admin client ...</a></p>");
            }
            // append footer
            strBody.append("<br><br><b>System information:</b><br><br>");
            strBody.append("<b>Server:</b> " + serverName + " / " + WGACore.getReleaseString() + "<br>");
            strBody.append("<b>Host:</b> " + hostname + "<br>");
            strBody.append("<b>Operation System:</b> " + System.getProperty("os.name") + " Version "
                    + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")<br>");
            strBody.append("<b>Java virtual machine:</b> " + System.getProperty("java.vm.name") + " Version "
                    + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor")
                    + ")");

            strBody.append("</body></html>");
            body.setText(strBody.toString());
            body.setHeader("MIME-Version", "1.0");
            body.setHeader("Content-Type", "text/html");

            content.addBodyPart(body);
            AppLog appLog = WGA.get(this).service(AppLog.class);

            if (notification.isAttachLogfile()) {
                MimeBodyPart attachmentBody = new MimeBodyPart();

                StringWriter applog = new StringWriter();
                int applogSize = appLog.getLinesCount();
                int offset = applogSize - notification.getLogfileLines();
                if (offset < 0) {
                    offset = 1;
                }
                appLog.writePage(offset, notification.getLogfileLines(), applog, LogLevel.LEVEL_INFO, false);

                attachmentBody.setDataHandler(new DataHandler(applog.toString(), "text/plain"));
                attachmentBody.setFileName("wga.log");
                content.addBodyPart(attachmentBody);
            }
            msg.setContent(content);

            // Send mail
            Thread mailThread = new Thread(new AsyncMailSender(msg), "WGAMailSender");
            mailThread.start();
        } catch (Exception e) {
            getLog().error("Unable to send wga admin notification.", e);
        }
    }
}

From source file:com.sonicle.webtop.mail.Service.java

private MimeMessage createMessage(MailAccount account, InternetAddress from, String subject)
        throws MessagingException {
    try {//from   w  w  w  .ja  va2 s  . c  om
        subject = MimeUtility.encodeText(subject);
    } catch (Exception ex) {
    }

    MimeMessage message = new MimeMessage(account.getMailSession());
    message.setSubject(subject);
    message.addFrom(new InternetAddress[] { from });
    message.setSentDate(new java.util.Date());
    return message;
}

From source file:com.sonicle.webtop.mail.Service.java

public void processEditEmailSubject(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    try {/*from w w w.  jav  a 2 s. com*/
        String newSubject = ServletUtils.getStringParameter(request, "subject", true);
        int messageId = ServletUtils.getIntParameter(request, "messageId", true);
        String currentFolder = ServletUtils.getStringParameter(request, "currentFolder", true);

        MailAccount account = getAccount(request);
        FolderCache folderCache = account.getFolderCache(currentFolder);
        Message currentMessage = folderCache.getMessage(messageId);

        MimeMessage newMessage = new MimeMessage((MimeMessage) currentMessage);
        newMessage.setSubject(newSubject);
        folderCache.appendMessage(newMessage);
        folderCache.deleteMessages(new long[] { messageId }, true);

        new JsonResult(true).printTo(out);

    } catch (Exception ex) {
        logger.error("Error in EditEmailSubject", ex);
        new JsonResult(ex).printTo(out);
    }
}