Example usage for javax.mail.internet MimeMessage setContent

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

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this Message's content.

Usage

From source file:com.wso2telco.workflow.notification.EmailService.java

public void sendEmail(final String emailAddress, final String subject, final String content) {

    new Thread() {
        @Override/*from ww w  . ja va  2s  .  c o  m*/
        public void run() {
            Map<String, String> workflowProperties = WorkflowProperties.loadWorkflowPropertiesFromXML();
            String emailHost = workflowProperties.get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_HOST);
            String fromEmailAddress = workflowProperties
                    .get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_ADDRESS);
            String fromEmailPassword = workflowProperties
                    .get(Constants.KEY_WORKFLOW_EMAIL_NOTIFICATION_FROM_PASSWORD);

            Properties props = System.getProperties();
            props.put("mail.smtp.host", emailHost);
            props.put("mail.smtp.user", fromEmailAddress);
            props.put("mail.smtp.password", fromEmailPassword);
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.auth", "true");

            try {
                Session session = Session.getDefaultInstance(props, null);
                InternetAddress toAddress = new InternetAddress(emailAddress);

                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(fromEmailAddress));
                message.addRecipient(Message.RecipientType.TO, toAddress);
                message.setSubject(subject);
                message.setContent(content, "text/html; charset=UTF-8");

                Transport transport = session.getTransport("smtp");
                transport.connect(emailHost, fromEmailAddress, fromEmailPassword);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

            } catch (Exception e) {
                log.error("Email sending failed. ", e);
            }
        }
    }.start();
}

From source file:au.org.ala.biocache.service.EmailService.java

/**
 * Sends an email with the supplied details. 
 * /*from ww w  .j  a  v  a  2 s  .c  om*/
 * @param recipient
 * @param subject
 * @param content
 * @param sender
 */
public void sendEmail(String recipient, String subject, String content, String sender) {

    logger.debug("Send email to : " + recipient);
    logger.debug("Body: " + content);
    Session session = Session.getDefaultInstance(properties);

    try {

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        message.setSubject(subject);
        message.setContent(content, "text/html");
        Transport.send(message);
    } catch (Exception e) {
        logger.error("Unable to send email to " + recipient + ".\n" + content, e);
    }
}

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

/**
 * :?/*ww w.  j av  a2  s.  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.mycompany.login.mb.EmailBean.java

public void envia() throws AddressException, MessagingException {
    Session session = Session.getInstance(this.propriedades, this.authentication);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("anderson.freitas@lifemed.com.br"));
    message.setRecipients(Message.RecipientType.TO, "anderson.freitas@lifemed.com.br");
    message.setSentDate(new Date());
    message.setSubject("Teste envio jsf");
    message.setContent("Sua solicitao foi aprovada: OS n" + this.os, "text/plain");

    Transport.send(message);//from   w w  w .  j a  v a  2  s  . c  o  m

}

From source file:org.apache.camel.component.google.mail.GmailUsersMessagesIntegrationTest.java

private Message createTestEmail() throws MessagingException, IOException {
    com.google.api.services.gmail.model.Profile profile = requestBody(
            "google-mail://users/getProfile?inBody=userId", CURRENT_USERID);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(javax.mail.Message.RecipientType.TO, profile.getEmailAddress());
    mm.setSubject("Hello from camel-google-mail");
    mm.setContent("Camel rocks!", "text/plain");
    Message createMessageWithEmail = createMessageWithEmail(mm);
    return createMessageWithEmail;
}

From source file:org.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java

@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
        throws IOException, InterruptedException {
    final EnvVars env = build.getEnvironment(listener);
    final String charset = Mailer.descriptor().getCharset();
    final MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    try {//from   w ww.  j  a v  a 2s  .  co  m
        msg.setFrom(Mailer.StringToAddress(JenkinsLocationConfiguration.get().getAdminAddress(), charset));
        msg.setContent("", "text/plain");
        msg.setSentDate(new Date());
        String actualReplyTo = env.expand(replyTo);
        if (StringUtils.isBlank(actualReplyTo)) {
            actualReplyTo = Mailer.descriptor().getReplyToAddress();
        }
        if (StringUtils.isNotBlank(actualReplyTo)) {
            msg.setReplyTo(new Address[] { Mailer.StringToAddress(actualReplyTo, charset) });
        }
        msg.setRecipients(RecipientType.TO, toInternetAddresses(listener, env.expand(tos), charset));
        msg.setRecipients(RecipientType.CC, toInternetAddresses(listener, env.expand(ccs), charset));
        msg.setRecipients(RecipientType.BCC, toInternetAddresses(listener, env.expand(bccs), charset));
        msg.setSubject(env.expand(subject), charset);
        msg.setText(env.expand(text), charset);
        Transport.send(msg);
    } catch (final MessagingException e) {
        listener.getLogger().println(Messages.SendMail_FailedToSend());
        e.printStackTrace(listener.error(e.getMessage()));
        return false;
    }
    listener.getLogger().println(Messages.SendMail_SentSuccessfully());
    return true;
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void sendGRUP(String from, String password, String bcc, String sub, String msg, String filename)
        throws Exception {
    //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, password);
        }//from w  ww.j a  v  a2 s.  com
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        //message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));

        message.setSubject(sub);
        message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automat");

        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);
        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        message.setContent(writer.toString(), "text/html");

        //send message  
        Transport.send(message);
        System.out.println("message sent successfully");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}

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 w  w  .j a  v a  2  s.  com
        // 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:davmail.smtp.TestSmtp.java

public void testSendHtmlMessage() throws IOException, MessagingException, InterruptedException {
    String body = "Test html message <font color=\"#ff0000\">red</font>";
    MimeMessage mimeMessage = new MimeMessage((Session) null);
    mimeMessage.addHeader("To", Settings.getProperty("davmail.to"));
    mimeMessage.setSubject("Test html message");
    mimeMessage.setContent(body, "text/html");
    sendAndCheckMessage(mimeMessage);// w w w. j  a  v a  2s  .  co  m
}

From source file:com.norconex.jef4.mail.SimpleMailer.java

/**
 * Sends an email./*ww w .ja  va  2 s .  c  om*/
 * @param recipients email recipients ("To" field)
 * @param subject email subject
 * @param body email body (content)
 * @throws MessagingException problem sending email
 */
public final void send(final String[] recipients, final String subject, final String body)
        throws MessagingException {
    if (recipients == null || recipients.length == 0) {
        throw new IllegalArgumentException("No mail recipient provided.");
    }
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sender));
    for (int i = 0; i < recipients.length; i++) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients[i]));
    }
    message.setSubject(subject);
    message.setContent(body, contentType);
    Transport.send(message);
}