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:EmailJndiServlet.java

private void sendMessage(String to, String from, String subject, String bodyContent) throws Exception {

    Message mailMsg = null;/*from  w w  w. ja v  a2  s  . c o m*/

    synchronized (mailSession) {

        mailMsg = new MimeMessage(mailSession);//a new email message
    }

    InternetAddress[] addresses = null;

    try {

        if (to != null) {

            //throws 'AddressException' if the 'to' email address
            //violates RFC822 syntax
            addresses = InternetAddress.parse(to, false);

            mailMsg.setRecipients(Message.RecipientType.TO, addresses);

        } else {

            throw new MessagingException("The mail message requires a 'To' address.");

        }

        if (from != null)
            mailMsg.setFrom(new InternetAddress(from));

        if (subject != null)
            mailMsg.setSubject(subject);

        if (bodyContent != null)
            mailMsg.setText(bodyContent);

        //Finally, send the mail message; throws a 'SendFailedException' 
        //if any of the message's recipients have an invalid adress
        Transport.send(mailMsg);

    } catch (Exception exc) {

        throw exc;
    }
}

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

/**
 * Sends an email with the supplied details. 
 * /*from   w  ww  .jav a  2s  . c o m*/
 * @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:com.cloudbees.demo.beesshop.service.MailService.java

public void sendProductEmail(Product product, String recipient, String cocktailPageUrl)
        throws MessagingException {

    Message msg = new MimeMessage(mailSession);

    msg.setFrom(fromAddress);/*  w  w  w  . j av  a 2s.  c  o m*/
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

    msg.setSubject("[BeesShop] Check this product: " + product.getName());
    String message = product.getName() + "\n" //
            + "--------------------\n" //
            + "\n" //
            + Strings.nullToEmpty(product.getDescription()) + "\n" //
            + "\n" //
            + cocktailPageUrl;
    msg.setContent(message, "text/plain");

    mailSession.getTransport().send(msg);
    auditLogger.info("Sent to {} product '{}'", recipient, product.getName());
    sentEmailCounter.incrementAndGet();
}

From source file:com.threewks.thundr.mail.JavaMailMailer.java

@Override
protected void sendInternal(Map.Entry<String, String> from, Map.Entry<String, String> replyTo,
        Map<String, String> to, Map<String, String> cc, Map<String, String> bcc, String subject, Object body,
        List<Attachment> attachments) {
    try {//from www. ja v a  2  s .  c  o m
        Session emailSession = getSession();

        Message message = new MimeMessage(emailSession);
        message.setFrom(emailAddress(from));
        if (replyTo != null) {
            message.setReplyTo(new Address[] { emailAddress(replyTo) });
        }

        message.setSubject(subject);

        BasicViewRenderer viewRenderer = render(body);
        String content = viewRenderer.getOutputAsString();
        String contentType = ContentType.cleanContentType(viewRenderer.getContentType());
        contentType = StringUtils.isBlank(contentType) ? ContentType.TextHtml.value() : contentType;

        if (Expressive.isEmpty(attachments)) {
            message.setContent(content, contentType);
        } else {
            Multipart multipart = new MimeMultipart("mixed"); // subtype must be "mixed" or inline & regular attachments won't play well together
            addBody(multipart, content, contentType);
            addAttachments(multipart, attachments);
            message.setContent(multipart);
        }

        addRecipients(to, message, RecipientType.TO);
        addRecipients(cc, message, RecipientType.CC);
        addRecipients(bcc, message, RecipientType.BCC);

        sendMessage(message);
    } catch (MessagingException e) {
        throw new MailException(e, "Failed to send an email: %s", e.getMessage());
    }
}

From source file:de.tuttas.servlets.MailSender.java

private void transmitMail(MailObject mo) throws MessagingException {

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(Config.getInstance().user, Config.getInstance().pass);
        }//w w  w .  j  a  va2  s .  co m
    };
    Session session = Session.getInstance(properties, auth);
    // creates a new e-mail message
    MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mo.getFrom()));
    InternetAddress[] toAddresses = mo.getRecipient();
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    InternetAddress[] bccAdresses = mo.getBcc();
    InternetAddress[] ccAdresses = mo.getCC();

    if (bccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.BCC, bccAdresses);
    if (ccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.CC, ccAdresses);
    msg.setSubject(mo.getSubject(), "UTF-8");

    msg.setSentDate(new Date());
    msg.setContent(mo.getContent(), "text/plain; charset=UTF-8");
    // sends the e-mail
    // TODO Kommentar entfernen
    Transport.send(msg);
}

From source file:ru.codemine.ccms.mail.EmailService.java

public void sendSimpleMessage(String address, String subject, String content) {
    try {//  w  w  w. j a  v  a2  s .c  om
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.mime.charset", "UTF-8");
        props.put("mail.smtp.ssl.enable", ssl);

        Session session = Session.getInstance(props, new EmailAuthenticator(username, password));

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username, ""));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(address));
        message.setSubject(subject);
        message.setText(content, "utf-8", "html");
        Transport transport = session.getTransport("smtp");
        transport.connect();
        transport.sendMessage(message, message.getAllRecipients());
    } catch (MessagingException | UnsupportedEncodingException ex) {
        log.error(
                "?  ? email,  : "
                        + ex.getLocalizedMessage());
        ex.printStackTrace();
    }

}

From source file:de.fzi.ALERT.actor.ActionActuator.MailService.java

public void sendEmail(Authenticator auth, String address, String subject, String content) {
    try {//from w  ww  .  j a  va 2s. co  m
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props, auth);
        // -- Create a new message --
        Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false));

        // -- Set the subject and body text --
        msg.setSubject(subject);
        msg.setText(content);

        // -- Set some other header information --
        msg.setHeader("X-Mailer", "LOTONtechEmail");
        msg.setSentDate(new Date());

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

        System.out.println("An announce Mail has been send to " + address);
    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.MimeMessageResponse.java

public MimeMessageResponse(WsdlRequest wsdlRequest, final TimeablePostMethod postMethod,
        String requestContent) {/*  www.jav a 2  s . c o m*/
    this.wsdlRequest = wsdlRequest;
    this.requestContent = requestContent;
    this.timeTaken = postMethod.getTimeTaken();
    responseContentLength = postMethod.getResponseContentLength();

    try {
        initHeaders(postMethod);

        MimeMultipart mp = new MimeMultipart(new PostResponseDataSource(postMethod));
        message = new MimeMessage(HttpClientRequestTransport.JAVAMAIL_SESSION);
        message.setContent(mp);

        Header h = postMethod.getResponseHeader("Content-Type");
        HeaderElement[] elements = h.getElements();

        String rootPartId = null;

        for (HeaderElement element : elements) {
            if (element.getName().toUpperCase().startsWith("MULTIPART/")) {
                NameValuePair parameter = element.getParameterByName("start");
                if (parameter != null)
                    rootPartId = parameter.getValue();
            }
        }

        for (int c = 0; c < mp.getCount(); c++) {
            BodyPart bodyPart = mp.getBodyPart(c);

            if (bodyPart.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                MimeMultipart mp2 = new MimeMultipart(new BodyPartDataSource(bodyPart));
                for (int i = 0; i < mp2.getCount(); i++) {
                    result.add(new BodyPartAttachment(mp2.getBodyPart(i)));
                }
            } else {
                BodyPartAttachment attachment = new BodyPartAttachment(bodyPart);

                String[] contentIdHeaders = bodyPart.getHeader("Content-ID");
                if (contentIdHeaders != null && contentIdHeaders.length > 0
                        && contentIdHeaders[0].equals(rootPartId)) {
                    rootPart = attachment;
                } else
                    result.add(attachment);
            }
        }

        // if no explicit root part has been set, use the first one in the result
        if (rootPart == null)
            rootPart = result.remove(0);

        if (wsdlRequest.getSettings().getBoolean(HttpSettings.INCLUDE_RESPONSE_IN_TIME_TAKEN))
            this.timeTaken = postMethod.getTimeTakenUntilNow();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ips1ap101.ejb.core.mail.MailerBean.java

@Override
public Message sendMessage(String addressList, String subject, String text) throws MessagingException {
    if (EA.isMailingEnabled()) {
    } else {/*from  w w w  . jav  a2 s  . c  om*/
        return null;
    }
    if (StringUtils.isBlank(addressList)) {
        throw new InvalidParameterException("addressList");
    }
    if (StringUtils.isBlank(subject)) {
        throw new InvalidParameterException("subject");
    }
    if (StringUtils.isBlank(text)) {
        throw new InvalidParameterException("text");
    }
    Address[] internetAddressList = InternetAddress.parse(addressList, false);
    Date timeStamp = new Date();
    Message message = new MimeMessage(session);
    message.setFrom();
    message.setHeader("X-Mailer", "JavaMail");
    message.setRecipients(Message.RecipientType.TO, internetAddressList);
    message.setSentDate(timeStamp);
    message.setSubject(subject);
    message.setText(text);
    Transport.send(message);
    return message;
}

From source file:mailhost.StartApp.java

public void sendEmail(String to, String subject, String body)
        throws UnsupportedEncodingException, MessagingException {

    System.out.println(String.format("Sending notification email recipients " + "to  " + to + " subject  "
            + subject + "host " + mailhost));

    if (StringUtils.isBlank(to))
        throw new IllegalArgumentException("The email request should have at least one recipient");

    Properties properties = new Properties();
    properties.setProperty("mail.smtp.host", mailhost);

    Session session = Session.getDefaultInstance(properties);
    Address[] a = new InternetAddress[1];
    a[0] = new InternetAddress("test@matson.com");

    MimeMessage message = new MimeMessage(session);

    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.addFrom(a);/*from ww w. ja  v  a2 s  .  co  m*/

    message.setSubject(subject);
    message.setContent(body, "text/html; charset=utf-8");
    //message.setText(body);

    // Send message
    Transport.send(message);
    System.out.println("Email sent.");
}