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.scape_project.planning.application.BugReport.java

/**
 * Method responsible for sending a bug report per mail.
 * /*w ww .  ja v  a2s .c  o m*/
 * @param userEmail
 *            email address of the user.
 * @param errorDescription
 *            error description given by the user.
 * @param exception
 *            the exception causing the bug/error.
 * @param requestUri
 *            request URI where the error occurred
 * @param location
 *            the location of the application where the error occurred
 * @param applicationName
 *            application name
 * @param plan
 *            the plan where the exception occurred
 * @throws MailException
 *             if the bug report could not be sent
 */
public void sendBugReport(String userEmail, String errorDescription, Throwable exception, String requestUri,
        String location, String applicationName, Plan plan) throws MailException {

    try {
        Properties props = System.getProperties();

        props.put("mail.smtp.host", config.getString("mail.smtp.host"));
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(config.getString("mail.from")));
        message.setRecipient(RecipientType.TO, new InternetAddress(config.getString("mail.feedback")));

        message.setSubject("[" + applicationName + "] from " + location);

        StringBuilder builder = new StringBuilder();
        // Date
        builder.append("Date: ").append(DATE_FORMAT.format(new Date())).append("\n\n");

        // User info
        if (user == null) {
            builder.append("No user available.\n\n");
        } else {
            builder.append("User: ").append(user.getUsername()).append("\n");
            if (user.getUserGroup() != null) {
                builder.append("Group: ").append(user.getUserGroup().getName()).append("\n");
            }
        }
        builder.append("UserMail: ").append(userEmail).append("\n\n");

        // Plan
        if (plan == null) {
            builder.append("No plan available.").append("\n\n");
        } else {
            builder.append("Plan ID: ").append(plan.getPlanProperties().getId()).append("\n");
            builder.append("Plan name: ").append(plan.getPlanProperties().getName()).append("\n\n");
        }

        // Description
        builder.append("Description:\n");
        builder.append(SEPARATOR_LINE);
        builder.append(errorDescription).append("\n");
        builder.append(SEPARATOR_LINE).append("\n");

        // Request URI
        builder.append("Request URI: ").append(requestUri).append("\n\n");

        // Exception
        if (exception == null) {
            builder.append("No exception available.").append("\n");
        } else {
            builder.append("Exception type: ").append(exception.getClass().getCanonicalName()).append("\n");
            builder.append("Exception message: ").append(exception.getMessage()).append("\n");

            StringWriter writer = new StringWriter();
            exception.printStackTrace(new PrintWriter(writer));

            builder.append("Stacktrace:\n");
            builder.append(SEPARATOR_LINE);
            builder.append(writer.toString());
            builder.append(SEPARATOR_LINE);
        }

        message.setText(builder.toString());
        message.saveChanges();

        Transport.send(message);
        log.debug("Bug report mail from user {} sent successfully to {}", user.getUsername(),
                config.getString("mail.feedback"));

        String userMessage = "Bugreport sent. Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible.";
        Notification notification = new Notification(UUID.randomUUID().toString(), new Date(), "PLATO",
                userMessage, user);
        try {
            utx.begin();
            em.persist(notification);
            utx.commit();
        } catch (Exception e) {
            log.error("Failed to store user notification for bugreport of {}", user.getUsername(), e);
        }

    } catch (MessagingException e) {
        throw new MailException("Error sending bug report mail from user " + user.getUsername() + " to "
                + config.getString("mail.feedback"), e);
    }
}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

public void sendMail(Mail mail) {
    LOG.debug("sendEmail() to: " + mail.getRecipient());
    try {//from w w w .ja v  a2s .c  o  m
        Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
        session.setDebug(false);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(m_bag.m_fromAddress);
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
        msg.setSubject(mail.getSubject());
        msg.setSentDate(new Date());

        Multipart mp = new MimeMultipart();

        MimeBodyPart txtmbp = new MimeBodyPart();
        txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE);
        mp.addBodyPart(txtmbp);

        List<String> attachments = mail.getAttachments();
        for (Iterator<String> it = attachments.iterator(); it.hasNext();) {
            MimeBodyPart mbp = new MimeBodyPart();
            String filename = it.next();
            FileDataSource fds = new FileDataSource(filename);
            mbp.setDataHandler(new DataHandler(fds));
            mbp.setFileName(MimeUtility.encodeText(fds.getName()));
            mp.addBodyPart(mbp);
        }

        msg.setContent(mp);

        if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null)
                && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) {
            cheat(msg,
                    m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@")));
        }

        Transport.send(msg);

        LOG.info("Successfully send the mail to " + mail.getRecipient());

    } catch (Throwable e) {

        LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e);
        LOG.debug("Details:", e);
    }
}

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from   ww  w.  j  a  va  2  s . co m
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-M")) {
            mailhost = argv[++optind];
        } else if (argv[optind].equals("-f")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = argv[++optind];
        } else if (argv[optind].equals("-c")) {
            cc = argv[++optind];
        } else if (argv[optind].equals("-b")) {
            bcc = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length) {
            // XXX - concatenate all remaining arguments
            to = argv[optind];
            System.out.println("To: " + to);
        } else {
            System.out.print("To: ");
            System.out.flush();
            to = in.readLine();
        }
        if (subject == null) {
            System.out.print("Subject: ");
            System.out.flush();
            subject = in.readLine();
        } else {
            System.out.println("Subject: " + subject);
        }

        Properties props = System.getProperties();
        // XXX - could use Session.getTransport() and Transport.connect()
        // XXX - assume we're using SMTP
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);

        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);

        // construct the message
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

        msg.setSubject(subject);

        collect(in, msg);

        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());

        // send the thing off
        Transport.send(msg);

        System.out.println("\nMail was sent successfully.");

        // Keep a copy, if requested.

        if (record != null) {
            // Get a Store object
            Store store = null;
            if (url != null) {
                URLName urln = new URLName(url);
                store = session.getStore(urln);
                store.connect();
            } else {
                if (protocol != null)
                    store = session.getStore(protocol);
                else
                    store = session.getStore();

                // Connect
                if (host != null || user != null || password != null)
                    store.connect(host, user, password);
                else
                    store.connect();
            }

            // Get record Folder. Create if it does not exist.
            Folder folder = store.getFolder(record);
            if (folder == null) {
                System.err.println("Can't get record folder.");
                System.exit(1);
            }
            if (!folder.exists())
                folder.create(Folder.HOLDS_MESSAGES);

            Message[] msgs = new Message[1];
            msgs[0] = msg;
            folder.appendMessages(msgs);

            System.out.println("Mail was recorded successfully.");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:it.ozimov.springboot.templating.mail.utils.EmailToMimeMessageTest.java

@Test
public void sendMailWithoutTemplate() throws MessagingException, IOException {

    // Arrange/*w  w  w.  j a  v  a 2  s . c o m*/
    when(javaMailSender.createMimeMessage()).thenReturn(new MimeMessage((Session) null));

    final Email email = getSimpleMail();

    // Act
    final MimeMessage sentMessage = emailToMimeMessage.apply(email);

    // Assert
    validateFrom(email, sentMessage);
    validateReplyTo(email, sentMessage);
    validateTo(email, sentMessage);
    validateCc(email, sentMessage);
    validateBcc(email, sentMessage);
    validateSubject(email, sentMessage);
    validateBody(email, sentMessage);

    verify(javaMailSender, times(1)).createMimeMessage();
}

From source file:com.google.ie.web.controller.EmailController.java

/**
 * Send mail to the given email id with the provided text and subject.
 * /*from www  . j a  v a 2s.co  m*/
 * @param recepientEmailId email id of the recepient
 * @param emailText text of the mail
 * @param subject subject of the mail
 * @throws IdeasExchangeException
 * @throws MessagingException
 * @throws AddressException
 */
protected void sendMail(String recepientEmailId, String emailText, String subject)
        throws IdeasExchangeException, AddressException, MessagingException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);

    Message message = new MimeMessage(session);

    message.setRecipient(RecipientType.TO, new InternetAddress(recepientEmailId));
    message.setFrom(new InternetAddress(getAdminMailId()));

    message.setText(emailText);
    message.setSubject(subject);

    Transport.send(message);
    log.info("Mail sent successfully to : " + recepientEmailId + " for " + subject);
}

From source file:ua.aits.sdolyna.controller.MainController.java

@RequestMapping(value = { "/sendmail/", "/sendmail" }, method = RequestMethod.GET)
public @ResponseBody String sendMail(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    request.setCharacterEncoding("UTF-8");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String text = request.getParameter("text");
    final String username = "office@crc.org.ua";
    final String password = "crossroad2000";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
            return new javax.mail.PasswordAuthentication(username, password);
        }/*w  w  w .  j av a2s  .  c o  m*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(email));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("sonyachna-dolyna@ukr.net"));
        message.setSubject("E-mail ? ?:");
        message.setText("?: " + name + "\nEmail: " + email + "\n\n" + text);
        Transport.send(message);
        return "done";
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:info.raack.appliancedetection.common.email.SMTPEmailSender.java

public void sendGeneralEmail(String recipientEmail, String subject, String body) {
    Session session = Session.getDefaultInstance(emailProperties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*from   ww w.j a v  a 2 s .  c o m*/
    });

    Message message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail));
        message.setSubject(subject + (!environment.equals("prod") ? " [" + environment + "]" : ""));
        message.setText(body);
    } catch (Exception e) {
        throw new RuntimeException("Could not create message", e);
    }

    emailQueue.add(message);
}

From source file:com.app.mail.DefaultMailSender.java

private static Message _populateContactMessage(String emailAddress, String messageBody, Session session)
        throws Exception {

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(emailAddress));

    message.addRecipient(Message.RecipientType.TO,
            new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS));

    message.setSubject("You Have A New Message From " + emailAddress);
    message.setText(messageBody);//w  ww  .  ja va2  s .  c o  m

    return message;
}

From source file:com.cosmicpush.plugins.smtp.EmailMessage.java

/**
 * @param session the applications current session.
 * @throws EmailMessageException in response to any other type of exception.
 *//*from  w  w w.  j  a  v a  2s  .  c om*/
@SuppressWarnings({ "ConstantConditions" })
protected void send(Session session) throws EmailMessageException {
    try {

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

        //set some of the basic attributes.
        msg.setFrom(fromAddress);
        msg.setRecipients(Message.RecipientType.TO, ReflectUtils.toArray(InternetAddress.class, toAddresses));
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        if (replyToAddress.isEmpty() == false) {
            msg.setReplyTo(ReflectUtils.toArray(InternetAddress.class, replyToAddress));
        }

        // create the Multipart and add set it as the content of the message
        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // create and fill the HTML part of the messgae if it exists
        if (html != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(html, "UTF-8", "html");
            multipart.addBodyPart(bodyPart);
        }

        // create and fill the text part of the messgae if it exists
        if (text != null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(text, "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        if (html == null && text == null) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText("", "UTF-8", "plain");
            multipart.addBodyPart(bodyPart);
        }

        // remove any nulls from the list of attachments.
        while (attachments.remove(null)) {
            /* keep going */ }

        // Attach any files that we have, making sure that they exist first
        for (File file : attachments) {
            if (file.exists() == false) {
                throw new EmailMessageException("The file \"" + file.getAbsolutePath() + "\" does not exist.");
            } else {
                MimeBodyPart attachmentPart = new MimeBodyPart();
                attachmentPart.attachFile(file);
                multipart.addBodyPart(attachmentPart);
            }
        }

        // send the message
        Transport.send(msg);

    } catch (EmailMessageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new EmailMessageException("Exception sending email\n" + toString(), ex);
    }
}

From source file:com.iorga.webappwatcher.watcher.RetentionLogWritingWatcher.java

protected void sendMailForEvent(final RetentionLogWritingEvent event) {
    log.info("Trying to send a mail for event " + event);

    new Thread(new Runnable() {
        @Override/*  ww w. ja v  a  2s.  c  o m*/
        public void run() {
            if (StringUtils.isEmpty(getMailSmtpHost()) || getMailSmtpPort() == null) {
                // no configuration defined, exiting
                log.error("Either SMTP host or port was not defined, not sending that mail");
                return;
            }
            // example from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
            final Properties props = new Properties();
            props.put("mail.smtp.host", getMailSmtpHost());
            props.put("mail.smtp.port", getMailSmtpPort());
            final Boolean auth = getMailSmtpAuth();
            Authenticator authenticator = null;
            if (BooleanUtils.isTrue(auth)) {
                props.put("mail.smtp.auth", "true");
                authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getMailSmtpUsername(), getMailSmtpPassword());
                    }
                };
            }
            if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "SSL")) {
                props.put("mail.smtp.socketFactory.port", getMailSmtpPort());
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            } else if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
            }

            final Session session = Session.getDefaultInstance(props, authenticator);

            try {
                final MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(getMailFrom()));
                message.setRecipients(RecipientType.TO, InternetAddress.parse(getMailTo()));
                message.setSubject(event.getReason());
                if (event.getContext() != null) {
                    final StringBuilder contextText = new StringBuilder();
                    for (final Entry<String, Object> contextEntry : event.getContext().entrySet()) {
                        contextText.append(contextEntry.getKey()).append(" = ").append(contextEntry.getValue())
                                .append("\n");
                    }
                    message.setText(contextText.toString());
                } else {
                    message.setText("Context null");
                }

                Transport.send(message);
            } catch (final MessagingException e) {
                log.error("Problem while sending a mail", e);
            }
        }
    }, RetentionLogWritingWatcher.class.getSimpleName() + ":sendMailer").start(); // send mail in an async way
}