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.otz.plugins.transport.aws.ses.SpringEmailSender.java

public void send(String templateName, Locale locale, String to, Map<String, String> parameters)
        throws MessagingException {

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(emailTemplateRepository.getFrom(templateName, locale)));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(emailTemplateRepository.getSubject(templateName, locale));
    msg.setContent(emailTemplateRepository.getContent(templateName, locale, parameters),
            emailTemplateRepository.getContentType(templateName, locale));

    try {/* w  ww .  j  a  v a 2  s . c om*/
        // Create a transport.
        transport = session.getTransport();
        transport.connect(emailConfigParameters.getHost(), emailConfigParameters.getAccessKey(),
                emailConfigParameters.getSecretKey());
        transport.sendMessage(msg, msg.getAllRecipients());

    } catch (Exception e) {

        // TODO deal with failure to send
        // send message to hipchat
        e.printStackTrace();
    }

}

From source file:edu.harvard.iq.dataverse.MailServiceBean.java

public void sendMail(String host, String from, String to, String subject, String messageText) {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(props, null);

    try {//  w w w  .  j  av a 2s  .  c  o  m
        MimeMessage msg = new MimeMessage(session);
        String[] recipientStrings = to.split(",");
        InternetAddress[] recipients = new InternetAddress[recipientStrings.length];
        try {
            msg.setFrom(new InternetAddress(from, charset));
            for (int i = 0; i < recipients.length; i++) {
                recipients[i] = new InternetAddress(recipientStrings[i], "", charset);
            }
        } catch (UnsupportedEncodingException ex) {
            logger.severe(ex.getMessage());
        }
        msg.setRecipients(Message.RecipientType.TO, recipients);
        msg.setSubject(subject, charset);
        msg.setText(messageText, charset);
        Transport.send(msg, recipients);
    } catch (AddressException ae) {
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        me.printStackTrace(System.out);
    }
}

From source file:com.srotya.tau.nucleus.qa.QAAlertRules.java

@Test
public void testASMTPServerAvailability() throws UnknownHostException, IOException, MessagingException {
    MimeMessage msg = new MimeMessage(Session.getDefaultInstance(new Properties()));
    msg.setFrom(new InternetAddress("alert@srotya.com"));
    msg.setRecipient(RecipientType.TO, new InternetAddress("alert@srotya.com"));
    msg.setSubject("test mail");
    msg.setContent("Hello", "text/html");
    Transport.send(msg);/*from ww w .  ja  va 2 s . c  o  m*/
    MailService ms = new MailService();
    ms.init(new HashMap<>());
    Alert alert = new Alert();
    alert.setBody("test");
    alert.setId((short) 0);
    alert.setMedia("test");
    alert.setSubject("test");
    alert.setTarget("alert@srotya.com");
    ms.sendMail(alert);
    assertEquals(2, AllQATests.getSmtpServer().getReceivedEmailSize());
    System.err.println("Mail sent");
}

From source file:com.fullmetalgalaxy.server.pm.PMServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    try {/*from  ww  w  . j  ava  2s . c o m*/
        // build message to send
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject("[FMG] no subject", "text/plain");
        msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        EbAccount fromAccount = null;

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if ("msg".equalsIgnoreCase(item.getFieldName())) {
                    msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("subject".equalsIgnoreCase(item.getFieldName())) {
                    msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("toid".equalsIgnoreCase(item.getFieldName())) {
                    EbAccount account = null;
                    try {
                        account = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (account != null) {
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(account.getEmail(), account.getPseudo()));
                    }
                }
                if ("fromid".equalsIgnoreCase(item.getFieldName())) {
                    try {
                        fromAccount = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (fromAccount != null) {
                        if (fromAccount.getAuthProvider() == AuthProvider.Google
                                && !fromAccount.isHideEmailToPlayer()) {
                            msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo()));
                        } else {
                            msg.setFrom(
                                    new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo()));
                        }
                    }
                }
            }
        }

        // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse(
        // "archive@fullmetalgalaxy.com" ) );
        Transport.send(msg);

    } catch (Exception e) {
        log.error(e);
        p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage());
        return;
    }

    p_response.sendRedirect("/genericmsg.jsp?title=Message envoye");
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

private MimeMessage prepareHTMLMimeMessage(InternetAddress internetAddressFrom, String subject, String htmlBody,
        List<LabelValueBean> attachments) throws Exception {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(internetAddressFrom);//from  ww  w  . j  av  a  2 s .  c o m
    msg.setHeader(XMAILER, xmailer);
    msg.setSubject(subject.trim(), mailEncoding);
    msg.setSentDate(new Date());

    MimeMultipart mimeMultipart = new MimeMultipart("related");

    BodyPart messageBodyPart = new MimeBodyPart();
    //Euro sign finally, shown correctly
    messageBodyPart.setContent(htmlBody, "text/html;charset=" + mailEncoding);
    mimeMultipart.addBodyPart(messageBodyPart);

    if (attachments != null && !attachments.isEmpty()) {
        LOGGER.debug("Use attachments: " + attachments.size());
        includeAttachments(mimeMultipart, attachments);
    }

    msg.setContent(mimeMultipart);

    return msg;
}

From source file:com.fstx.stdlib.common.messages.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *//*from  www . j a va 2 s.  c  om*/
public boolean send() {

    try {
        // 2005-11-27 RSC always requires authentication.
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.host", host.getAddress());
        /*
         * 2005-11-27 RSC
         * Since webmail.us is starting to make other ports available
         * as Comcast blocks port 25.
         */
        props.put("mail.smtp.port", host.getPort());

        Session s = Session.getInstance(props, null);

        MimeMessage messageOut = new MimeMessage(s);

        InternetAddress fromOut = new InternetAddress(from.getAddress());

        //reid 2004-12-20
        fromOut.setPersonal(from.getName());

        messageOut.setFrom(fromOut);

        InternetAddress toOut = new InternetAddress(this.to.getAddress());

        //reid 2004-12-20
        toOut.setPersonal(to.getName());

        messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut);

        messageOut.setSubject(message.getSubject());

        messageOut.setText(message.getMessage());

        if (host.useAuthentication()) {

            Transport transport = s.getTransport("smtp");
            transport.connect(host.getAddress(), host.getUsername(), host.getPassword());
            transport.sendMessage(messageOut, messageOut.getAllRecipients());
            transport.close();
        } else {

            Transport.send(messageOut);
        }

    } catch (Exception e) {
        log.info("\n\nMailSenderIMPL3: " + host.getAddress());
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return true;
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraPassed(String adresaSephora, String from, String grupTestContent,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }/*from  ww  w.  jav a  2  s .c  om*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(grupTestContent));
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);
        //  System.out.println("message sent successfully");
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {/*  w  w  w . jav  a 2  s  . co  m*/
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {/*from   w  w  w.  j  a v  a2s.c  om*/
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:com.mnt.base.mail.MailHelper.java

public static void sendMail(String mailType, String mailTos, Map<String, Object> infoMap) {

    String[] mailtemplate = loadMailTemplate(mailType);

    if (mailtemplate != null && mailtemplate.length == 2) {
        String from = BaseConfiguration.getProperty("mail_server_email");
        String subject = buildMailContent(mailtemplate[0], infoMap, false);
        String mailContent = buildMailContent(mailtemplate[1], infoMap, true);

        Message msg = new MimeMessage(smtpSession);
        try {/*www .ja v a 2 s  . c  om*/
            msg.setFrom(new InternetAddress(from));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTos, false));
            msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
            msg.setContent(mailContent, "text/html;charset=UTF-8");
            msg.setSentDate(new Date());

            Transport.send(msg);
        } catch (Exception e) {
            log.error("fail to send the mail: " + msg, e);
        }
    }
}