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:eu.planets_project.pp.plato.action.session.ExceptionAction.java

@RaiseEvent("exceptionHandled")
public String sendMail() {
    try {// w  w  w  .  ja v  a2  s .com
        log.debug(body);
        Properties props = System.getProperties();
        Properties mailProps = new Properties();
        mailProps.load(ExceptionAction.class.getResourceAsStream("/mail.properties"));
        props.put("mail.smtp.host", mailProps.getProperty("SMTPSERVER"));
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailProps.getProperty("FROM")));
        message.setRecipient(RecipientType.TO, new InternetAddress(mailProps.getProperty("TO")));
        String exceptionType = "Unknown";
        String exceptionMessage = "";
        String stackTrace = "";

        String host = ((HttpServletRequest) facesContext.getExternalContext().getRequest()).getLocalName();

        if (lastHandledException != null) {
            exceptionType = lastHandledException.getClass().getCanonicalName();
            exceptionMessage = lastHandledException.getMessage();
            StringWriter writer = new StringWriter();
            lastHandledException.printStackTrace(new PrintWriter(writer));
            stackTrace = writer.toString();
        }

        message.setSubject("[PlatoError] " + exceptionType + " at " + host);
        StringBuilder builder = new StringBuilder();
        builder.append("Date: " + format.format(new Date()) + "\n");
        builder.append("User: " + ((user == null) ? "Unknown" : user.getUsername()) + "\n");
        builder.append("ExceptionType: " + exceptionType + "\n");
        builder.append("ExceptionMessage: " + exceptionMessage + "\n\n");

        builder.append("UserMail:" + separatorLine + this.userEmail + separatorLine + "\n");
        builder.append("User Description:" + separatorLine + this.body + separatorLine + "\n");
        builder.append(stackTrace);
        message.setText(builder.toString());
        message.saveChanges();
        Transport.send(message);
        this.lastHandledException = null;
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Bugreport sent.",
                "Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible."));
    } catch (Exception e) {
        log.debug(e.getMessage(), e);
        facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Bugreport couldn't be sent",
                "Because of an enternal error your bug report couldn't be sent. We apologise for this and hope you are willing to inform us about this so we can fix the problem. "
                        + "Please send an email to plato@ifs.tuwien.ac.at with a "
                        + "description of what you have been doing at the time of the error."
                        + "Thank you very much!"));
        return null;
    }
    return "home";
}

From source file:Interface.FoodDistributionWorkArea.FoodDistributionWorkArea.java

public void sendEmail(String emailID, Food food) {

    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    final String username = "kunal.deora@gmail.com";//
    final String password = "adrika46";
    String text = "Hi Sir/Mam, " + '\n'
            + "You have received rewards points for the food you have donated. Details are listed below: "
            + '\n' + "Food Name:  " + food.getFoodName() + '\n' + "Food ID :" + food.getFoodBarCode() + '\n'
            + "Food Reward Points " + food.getRewardPoints() + '\n'
            + "If you have any queries you can contact us on +133333333333" + '\n'
            + "Thank you for helping for the betterment of society. Every little bite counts :) " + '\n';
    try {/*w  w  w  .ja  va  2  s  . c o  m*/
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(username, password);
            }
        });

        // -- Create a new message --
        javax.mail.Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress("kunal.deora@gmail.com"));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(emailID, false));
        msg.setSubject("Congratulations! You have received reward points !!!");
        msg.setText(text);
        msg.setSentDate(new Date());
        javax.mail.Transport.send(msg);
        System.out.println("Message sent.");
    } catch (javax.mail.MessagingException e) {
        System.out.println("Erreur d'envoi, cause: " + e);
    }

}

From source file:be.fedict.eid.dss.model.bean.TaskMDB.java

private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype,
        byte[] attachment) {
    LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\"");
    String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class);
    if (null == smtpServer || smtpServer.trim().isEmpty()) {
        LOG.warn("no SMTP server configured");
        return;//  w  w w  .  j  a v  a  2s .c  om
    }
    String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class);
    if (null == mailFrom || mailFrom.trim().isEmpty()) {
        LOG.warn("no mail from address configured");
        return;
    }
    LOG.debug("mail from: " + mailFrom);

    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.from", mailFrom);

    String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class);
    if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) {
        subject = "[" + mailPrefix.trim() + "] " + subject;
    }

    Session session = Session.getInstance(props, null);
    try {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom();
        mimeMessage.setRecipients(RecipientType.TO, mailTo);
        mimeMessage.setSubject(subject);
        mimeMessage.setSentDate(new Date());

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(messageBody);

        Multipart multipart = new MimeMultipart();
        // first part is body
        multipart.addBodyPart(mimeBodyPart);

        // second part is attachment
        if (null != attachment) {
            MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype);
            attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource));
            multipart.addBodyPart(attachmentMimeBodyPart);
        }

        mimeMessage.setContent(multipart);
        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("send failed, exception: " + e.getMessage(), e);
    }
}

From source file:it.infn.ct.security.actions.PassRecovery.java

private void sendMail(String code) throws MailException {
    javax.mail.Session session = null;//from w w  w. j  a va 2 s.  co m
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        String title = user.getTitle() == null ? "" : user.getTitle();

        mailMsg.setFrom(new InternetAddress(mailFrom));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(user.getPreferredMail(),
                title + user.getGivenname() + " " + user.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", title + " " + user.getGivenname() + " " + user.getSurname());
        mailBody = mailBody.replaceAll("_CODE_", code);

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail from address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

public AlvexEmailMessage(MimeMessage msg, UIDFolder folder) throws MessagingException {
    // FIXME creating new MimeMessage is a work-around
    // for more details see http://dmitriy-bannikov.blogspot.ru/2013/05/javaxmailmessagingexception-unable-to.html
    wrappedMessage = new SubethaEmailMessage(new MimeMessage(msg));
    parseMessage(msg, folder);//from   w w  w.  j  a va  2 s  . c  o  m
}

From source file:com.gcrm.util.mail.MailService.java

public void sendHtmlMail(String from, String[] to, String subject, String text, String[] fileNames,
        File[] files) throws Exception {
    List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName());
    EmailSetting emailSetting = null;// w w w  .j  a  v  a2  s .  c o m
    if (emailSettings != null && emailSettings.size() > 0) {
        emailSetting = emailSettings.get(0);
    } else {
        return;
    }
    if (from == null) {
        from = emailSetting.getFrom_address();
    }
    Session mailSession = createSmtpSession(emailSetting);

    if (mailSession != null) {
        Transport transport = mailSession.getTransport();
        MimeMessage msg = new MimeMessage(mailSession);
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text, true);
        if (fileNames != null && files != null) {
            String fileName = null;
            File file = null;
            for (int i = 0; i < fileNames.length; i++) {
                fileName = fileNames[i];
                file = files[i];
                if (fileName != null && file != null) {
                    helper.addAttachment(fileName, file);
                }
            }
        }
        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
    }

}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testSaveNewMessageRaw() throws IOException, MessagingException {
    File outputFile = File.createTempFile("mailUtilsTestRaw", ".eml");

    outputFile.deleteOnExit();//  w  ww.  j a  v a  2 s  . co  m

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

    message.addFrom(new InternetAddress[] { new InternetAddress("test@example.com") });
    message.addRecipients(RecipientType.TO, "recipient@example.com");
    message.setContent("test body", "text/plain");
    message.saveChanges();

    MailUtils.writeMessageRaw(message, new FileOutputStream(outputFile));

    MimeMessage loadedMessage = MailUtils.loadMessage(outputFile);

    String recipients = ArrayUtils.toString(loadedMessage.getRecipients(RecipientType.TO));

    assertEquals("{recipient@example.com}", recipients);

    String from = ArrayUtils.toString(loadedMessage.getFrom());

    assertEquals("{test@example.com}", from);
}

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

@Test
public void testCorruptMessage() throws Exception {
    MockMailetConfig mailetConfig = new MockMailetConfig("test");

    SendMailEventListenerImpl listener = new SendMailEventListenerImpl();

    mailetConfig.getMailetContext().setSendMailEventListener(listener);

    Mailet mailet = new BlackberrySMIMEAdapter();

    String template = FileUtils.readFileToString(new File("resources/templates/blackberry-smime-adapter.ftl"));

    autoTransactDelegator.setProperty("test@EXAMPLE.com", "pdfTemplate", template);

    mailetConfig.setInitParameter("log", "starting");
    /* use some dummy template because we must specify the default template */
    mailetConfig.setInitParameter("template", "sms.ftl");
    mailetConfig.setInitParameter("templateProperty", "pdfTemplate");

    mailet.init(mailetConfig);/*w w w  .j av  a 2 s .  c o m*/

    MockMail mail = new MockMail();

    mail.setState(Mail.DEFAULT);

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

    MimeBodyPart emptyPart = new MimeBodyPart();

    message.setContent(emptyPart, "text/plain");

    message.saveChanges();

    mail.setMessage(message);

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

    recipients.add(new MailAddress("123@EXAMPLE.com"));

    mail.setRecipients(recipients);

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

    mailet.service(mail);

    assertEquals(message, mail.getMessage());

    try {
        MailUtils.validateMessage(message);

        fail();
    } catch (IOException e) {
        // expected. The message should be corrupt
    }
}

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

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

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

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

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

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

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

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

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

        StringBuilder body = new StringBuilder(5000);

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

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

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

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

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

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

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

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

From source file:com.cubusmail.server.mail.MessageHandler.java

/**
 * @param session
 */
public void init(Session session) {

    init(session, new MimeMessage(session));
}