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.commoncoupon.mail.EmailProcessor.java

public Integer call() throws Exception {
    MimeMessage message = new MimeMessage(getSession());

    try {/*from   w w  w . j av a  2s .co m*/
        if (from != null && (from != null && from.trim() != "")) {
            InternetAddress sentFrom = new InternetAddress(from);
            message.setFrom(sentFrom);
            if (log.isDebugEnabled())
                log.debug("Email sent from: " + sentFrom);
        }

        if (to != null && to.length > 0) {
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                sendTo[i] = new InternetAddress((String) to[i]);
                if (log.isDebugEnabled())
                    log.debug("Sending e-mail to: " + to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, sendTo);
        }

        if (cc != null && cc.length > 0) {
            InternetAddress[] copyTo = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                copyTo[i] = new InternetAddress((String) cc[i]);
                if (log.isDebugEnabled())
                    log.debug("Copying e-mail to: " + cc[i]);
            }
            message.setRecipients(Message.RecipientType.CC, copyTo);
        }
        message.setSentDate(new Date());
        message.setSubject(subject);
        message.setContent(content, mimeType);
        Transport.send(message);
    } catch (Exception e) {
        log.error("Failed to send email.", e);
        return (1);
    }

    return (0);
}

From source file:com.jwm123.loggly.reporter.ReportMailer.java

public void send() throws MessagingException {
    if (StringUtils.isNotBlank(config.getMailServer()) && recipients.length > 0) {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.port", config.getMailPort().toString());
        props.setProperty("mail.smtp.host", config.getMailServer());
        if (StringUtils.isNotBlank(config.getMailUsername())
                && StringUtils.isNotBlank(config.getMailPassword())) {
            props.setProperty("mail.smtp.user", config.getMailUsername());
            props.setProperty("mail.smtp.password", config.getMailPassword());
        }/*from www .  j ava 2s  .  c o m*/

        Session session = Session.getDefaultInstance(props);

        MimeMessage message = new MimeMessage(session);
        message.addFrom(new Address[] { new InternetAddress(config.getMailFrom()) });
        message.setSubject(subject);
        for (String recipient : recipients) {
            message.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        MimeMultipart containingMultipart = new MimeMultipart("mixed");

        MimeMultipart messageMultipart = new MimeMultipart("alternative");
        containingMultipart.addBodyPart(newMultipartBodyPart(messageMultipart));

        messageMultipart.addBodyPart(newTextBodyPart(getText()));

        MimeMultipart htmlMultipart = new MimeMultipart("related");
        htmlMultipart.addBodyPart(newHtmlBodyPart(getHtml()));
        messageMultipart.addBodyPart(newMultipartBodyPart(htmlMultipart));

        containingMultipart.addBodyPart(addReportAttachment());

        message.setContent(containingMultipart);

        Transport.send(message);
    }
}

From source file:com.warsaw.data.controller.LoginController.java

private Message buildEmail(Session session, String to) throws Exception {
    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(EMAIL));

    // Set To: header field of the header.
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

    // Set Subject: header field
    message.setSubject("Testing Subject");

    // This mail has 2 part, the BODY and the embedded image
    MimeMultipart multipart = new MimeMultipart("related");

    // first part (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<img style='width:800px' src=\"cid:image1\"><br/>" + "Dzie dobry,<br/><br/>"
            + "witamy na portalu TrasyPoWarszawsku.pl, na ktrym zostalo "
            + "zaoone konto<br/> dla osoby o danych: Jan Marian Ptak. W celu zakoczenia procesu tworzenia "
            + "konta prosimy uy linku aktywacyjnego:<br/><br/>"
            + "<a href='https://test.puesc.gov.pl?link=Gkhh&%JK.'>https://test.puesc.gov.pl?link=Gkhh&%JK.</a><br/><br/>"
            + "Na wywietlonym ekranie prosz wprowadzi zdefiniowane przez siebie haso awaryjne. Po prawidowym"
            + " wprowadzeniu danych<br/> oraz  ustawieniu nowego  hasa dostpowego  konto  na portalu PUESC zostanie aktywowane.<br/>"
            + "Link aktywacyjny pozostanie wany przez 24 godziny od momentu  otrzymania niniejszej wiadomoci.<br/><br/>"
            + "<img style='width:800px' src=\"cid:image2\"><br/><br/>" + "Z powaaniem<br/><br/>"
            + "Zesp portalu PUESC<br/>" + "puesc@mofnet.gov.pl<br/>"
            + "<a href='http://puesc.gov.pl'>http://puesc.gov.pl</a>";

    messageBodyPart.setContent(htmlText, "text/html; charset=ISO-8859-2");
    // add it//  ww w . jav  a  2 s.  c  o  m
    multipart.addBodyPart(messageBodyPart);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("C:\\Users\\Pawel\\Desktop\\header.png");

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image1>");

    // add image to the multipart
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    //  URL url = new URL("http://ns3342351.ovh.net:8080/seap_lf_graphicsLayout_theme/images/refresh.png");
    // URLDataSource fds1 =new URLDataSource(url);
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image2>");
    multipart.addBodyPart(messageBodyPart);

    // put everything together
    message.setContent(multipart);

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    try {
        message.writeTo(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return message;
}

From source file:at.molindo.notify.channel.mail.AbstractMailClient.java

@Override
public synchronized void send(Dispatch dispatch) throws MailException {

    Message message = dispatch.getMessage();

    String recipient = dispatch.getParams().get(MailChannel.RECIPIENT);
    String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME);
    String subject = message.getSubject();

    try {/*from  w w  w  . ja  v  a  2  s .c  om*/
        MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) {
            @Override
            protected void updateMessageID() throws MessagingException {
                String domain = _from.getAddress();
                int idx = _from.getAddress().indexOf('@');
                if (idx >= 0) {
                    domain = domain.substring(idx + 1);
                }
                setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">");
            }
        };
        mm.setFrom(_from);
        mm.setSender(_from);

        InternetAddress replyTo = getReplyTo();
        if (replyTo != null) {
            mm.setReplyTo(new Address[] { replyTo });
        }
        mm.setHeader("X-Mailer", "molindo-notify");
        mm.setSentDate(new Date());

        mm.setRecipient(RecipientType.TO,
                new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName()));
        mm.setSubject(subject, CharsetUtils.UTF_8.displayName());

        if (_format == Format.HTML) {
            if (message.getType() == Type.TEXT) {
                throw new MailException("can't send HTML mail from TEXT message", false);
            }
            mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");
        } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) {
            mm.setText(message.getText(), CharsetUtils.UTF_8.displayName());
        } else if (_format == Format.MULTI) {
            MimeBodyPart html = new MimeBodyPart();
            html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html");

            MimeBodyPart text = new MimeBodyPart();
            text.setText(message.getText(), CharsetUtils.UTF_8.displayName());

            /*
             * The formats are ordered by how faithful they are to the
             * original, with the least faithful first and the most faithful
             * last. (http://en.wikipedia.org/wiki/MIME#Alternative)
             */
            MimeMultipart mmp = new MimeMultipart();
            mmp.setSubType("alternative");

            mmp.addBodyPart(text);
            mmp.addBodyPart(html);

            mm.setContent(mmp);
        } else {
            throw new NotifyRuntimeException(
                    "unexpected format (" + _format + ") or type (" + message.getType() + ")");
        }

        send(mm);

    } catch (final MessagingException e) {
        throw new MailException(
                "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e,
                isTemporary(e));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("utf8 unknown?", e);
    }
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendFiles(String to, String subject, String text, Collection<File> attachments)
        throws MessagingException {

    MimeMessage message = new MimeMessage(session);
    Transport t = session.getTransport("smtp");

    message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);//from  ww w .  java 2s. co  m
    message.setSentDate(new Date());
    if (attachments == null || attachments.size() < 1) {
        message.setText(text);
    } else {
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(text);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        for (File attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);
    }

    t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

    t.sendMessage(message, message.getAllRecipients());
    t.close();
}

From source file:fr.xebia.cocktail.MailService.java

public void sendCocktail(Cocktail cocktail, String recipient, String cocktailPageUrl)
        throws MessagingException {

    Message msg = new MimeMessage(mailSession);

    msg.setFrom(fromAddress);//  w  w w .  j a  v  a2s  .co  m
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

    msg.setSubject("[Cocktail] " + cocktail.getName());
    String message = cocktail.getName() + "\n" //
            + "--------------------\n" //
            + "\n" //
            + Strings.nullToEmpty(cocktail.getInstructions()) + "\n" //
            + "\n" //
            + cocktailPageUrl;
    msg.setContent(message, "text/plain");

    Transport.send(msg);
    auditLogger.info("Sent to {} cocktail '{}'", recipient, cocktail.getName());
    sentEmailCounter.incrementAndGet();
}

From source file:com.mimp.hibernate.HiberMail.java

public static void generateAndSendEmail2(String correo, String pass_plano, String user) {

    final String username = "formacionadopcion@gmail.com";
    final String password = "cairani.";

    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 PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from w  ww .  j a v  a 2 s. co  m
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("formacionadopcion@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(correo));
        message.setSubject("Sistema de adopciones");
        message.setText("Estimado solicitante,"
                + "\n\n Bienvenido al SISTEMA INFORM?TICO DEL REGISTRO NACIONAL DE ADOPCIONES, "
                + "sus credenciales para inscribirse al taller son las siguientes:" + "\n\n Usuario: " + user
                + "\n\n Contrasea: " + pass_plano
                //                    + "\n\n Para ingresar al sistema realizar lo siguiente, "
                //                    + "\n\n"
                //                    + "\n\n"
                //                    + "\n\n A. Click directamente en el siguiente link: "
                //                    + "\n\n"
                //                    + "\n\n       1. Click: http://app.mimp.gob.pe:8080/sirna "
                //                    + "\n\n       2. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n B. En caso no funcione el link, ingresar al sistema desde la pgina web: "
                //                    + "\n\n"
                //                    + "\n\n       1. Ingresar a la pgina web: www.mimp.gob.pe "
                //                    + "\n\n       2. En la barra de men Direcciones Generales? submen Vicemin. Pob. Vulnerables? seleccionar Adopciones? "
                //                    + "\n\n       3. Click en SIRNA Sistema Informtico del Registro Nacional de Adopciones? "
                //                    + "\n\n       4. Ingresar con el usuario y contrasea mencionadas lneas arriba. "
                //                    + "\n\n"
                //                    + "\n\n A travs del SIRNA usted podr realizar las siguientes acciones: "
                //                    + "\n\n"
                //                    + "\n\n       - Inscribirse a uno de los talleres programados. "
                //                    + "\n\n       - Descargar las lecturas de su taller. "
                //                    + "\n\n       - Revisar el estado del proceso de adopcin. "
                //                    + "\n\n       - Cambiar su contrasea. "
                //                    + "\n\n"
                //                    + "\n\n Para continuar con el proceso, por favor ingresar al sistema e inscribirse a uno de los talleres programados, hasta un da antes de inicio del taller y/o las bacantes se  "
                //                    + "\n\n encuentres disponibles. "
                + "\n\n"
                + "\n\n De tener alguna complicacin y no fue posible su ingreso al sistema, comunicarse inmediatamente con la unidad de adopcin correspondiente.  "
                + "\n\n" + "\n\n Atentamente, " + "\n\n" + "\n\n Direccin General de Adopciones " + "\n\n"
                + "\n\n Ministerio de la Mujer y Poblaciones Vulnerables " + "\n\n ");

        Transport.send(message);

        /*  } catch (Exception ex) {
         */
    } catch (Exception ex) {

    }

    /*catch (MessagingException e) {
     throw new RuntimeException(e);
     }*/
}

From source file:org.lf.yydp.service.film.BuyTicketService.java

/**
 * :?//from  w w  w .  ja v a 2s  . c  o  m
 * @param receiver
 */
public void sendEmail(String receiver) {
    Properties p = null;
    InputStream inputSteam = null;
    String senter = null;
    String Subject = null;
    String Content = null;
    try {
        p = new Properties();
        inputSteam = BuyTicketService.class.getClassLoader().getResourceAsStream("mail.properties");
        p.load(inputSteam);
        final String uname = p.getProperty("mail.uname");
        final String license = p.getProperty("mail.license");
        senter = p.getProperty("mail.senter");
        Subject = p.getProperty("mail.subject");
        Content = p.getProperty("mail.content");
        Authenticator authenticator = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uname, license);
            }
        };
        Session session = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(senter));
        msg.setRecipient(RecipientType.TO, new InternetAddress(receiver));
        msg.setSubject(Subject);
        msg.setContent(Content, "text/html;charset=utf-8");
        Transport.send(msg);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (inputSteam != null) {
                inputSteam.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }
}

From source file:com.adaptris.mail.MailSenderImp.java

@Override
public void newMessage() throws MailException {
    checkSession();
    message = new MimeMessage(session);
    attachments.clear();
}

From source file:ee.cyber.licensing.service.MailService.java

public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId)
        throws MessagingException, IOException, SQLException {
    License license = licenseRepository.findById(licenseId);
    List<Contact> contacts = contactRepository.findAll(license.getCustomer());
    List<String> receivers = getReceivers(mailbody, contacts);

    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }/*  ww w.jav  a 2s. co  m*/
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "License dude"));
    //mailMessage.setReplyTo(InternetAddress.parse(email, false));
    mailMessage.setSubject(mailbody.getSubject());
    //String emailBody = body + "<br><br> Regards, <br>Cybernetica team";
    mailMessage.setSentDate(new Date());

    for (String receiver : receivers) {
        mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
    }

    if (fileId != 0) {
        MailAttachment file = fileRepository.findById(fileId);
        if (file != null) {
            String fileName = file.getFileName();
            byte[] fileData = file.getData_b();
            if (fileName != null) {
                // Create a multipart message for attachment
                Multipart multipart = new MimeMultipart();
                // Body part
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(mailbody.getBody(), "text/html");
                multipart.addBodyPart(messageBodyPart);

                //Attachment part
                messageBodyPart = new MimeBodyPart();
                ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream");
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(fileName);
                multipart.addBodyPart(messageBodyPart);

                mailMessage.setContent(multipart);
            }
        }
    } else {
        mailMessage.setContent(mailbody.getBody(), "text/html");
    }

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);
}