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.tdclighthouse.commons.mail.util.MailClient.java

public void sendMail(String from, String[] to, Mail mail) throws MessagingException, AddressException {
    // a brief validation
    if ((from == null) || "".equals(from) || (to.length == 0) || (mail == null)) {
        throw new IllegalArgumentException();
    }//from  www . j av  a  2  s.  c  o  m
    Session session = getSession();

    // Define a new mail message
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    for (int i = 0; i < to.length; i++) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
    }
    message.setSubject(mail.getSubject(), "utf-8");

    // use a MimeMultipart as we need to handle the file attachments
    Multipart multipart = new MimeMultipart("alternative");

    if ((mail.getMessageBody() != null) && !"".equals(mail.getMessageBody())) {
        // add the message body to the mime message
        BodyPart textPart = new MimeBodyPart();
        textPart.setContent(mail.getMessageBody(), "text/plain; charset=utf-8"); // sets type to "text/plain"
        multipart.addBodyPart(textPart);
    }

    if (mail.getHtmlBody() != null) {
        BodyPart pixPart = new MimeBodyPart();
        pixPart.setContent(mail.getHtmlBody(), "text/html; charset=utf-8");
        multipart.addBodyPart(pixPart);
    }

    // add any file attachments to the message
    addAtachments(mail.getAttachments(), multipart);

    // Put all message parts in the message
    message.setContent(multipart);

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

}

From source file:jease.cms.service.Mails.java

/**
 * Sends an email synchronously./* w  ww . j  av  a  2  s.  com*/
 */
public void send(String sender, String recipients, String subject, String text) throws MessagingException {
    if (properties != null) {
        Session session = Session.getInstance(properties.asProperties(), new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getUser(), properties.getPassword());
            }
        });
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.setReplyTo(new InternetAddress[] { new InternetAddress(sender) });
        message.setRecipients(Message.RecipientType.TO, recipients);
        message.setSubject(subject, "utf-8");
        message.setSentDate(new Date());
        message.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        message.setHeader("Content-Transfer-Encoding", "quoted-printable");
        message.setText(text, "utf-8");
        Transport.send(message);
    }
}

From source file:org.vosao.utils.EmailUtil.java

/**
 * Send email with html content and attachments.
 * @param htmlBody/* w w w .j a v  a 2 s .co m*/
 * @param subject
 * @param fromAddress
 * @param fromText
 * @param toAddress
 * @return null if OK or error message.
 */
public static String sendEmail(final String htmlBody, final String subject, final String fromAddress,
        final String fromText, final String toAddress, final List<FileItem> files) {

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    try {
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlBody, "text/html");
        htmlPart.setHeader("Content-type", "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);
        for (FileItem item : files) {
            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setFileName(item.getFilename());
            String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename()));
            DataSource ds = new ByteArrayDataSource(item.getData(), mimeType);
            attachment.setDataHandler(new DataHandler(ds));
            mp.addBodyPart(attachment);
        }
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress, fromText));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress));
        msg.setSubject(subject, "UTF-8");
        msg.setContent(mp);
        Transport.send(msg);
        return null;
    } catch (AddressException e) {
        return e.getMessage();
    } catch (MessagingException e) {
        return e.getMessage();
    } catch (UnsupportedEncodingException e) {
        return e.getMessage();
    }
}

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  v  a2  s .  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:com.redhat.rhn.common.messaging.SmtpMail.java

/**
 * Create a mailer./*from   w  ww  .  ja v a  2 s . com*/
 */
public SmtpMail() {
    log.debug("Constructed new SmtpMail.");

    disallowedDomains = Config.get().getStringArray("web.disallowed_mail_domains");
    restrictedDomains = Config.get().getStringArray("web.restrict_mail_domains");

    Config c = Config.get();
    smtpHost = c.getString(ConfigDefaults.WEB_SMTP_SERVER, "localhost");
    String from = c.getString(ConfigDefaults.WEB_DEFAULT_MAIL_FROM);

    // Get system properties
    Properties props = System.getProperties();

    // Setup mail server
    props.put("mail.smtp.host", smtpHost);

    // Get session
    Session session = Session.getDefaultInstance(props, null);
    try {
        message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
    } catch (AddressException me) {
        String msg = "Malformed address in traceback configuration: " + from;
        log.warn(msg);
        throw new JavaMailException(msg, me);
    } catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " + me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}

From source file:com.basicservice.service.MailService.java

public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception {
    try {/*  w w w  .j  a v a2  s  .  c  o m*/
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", 587);
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SMTPAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        // mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        Multipart multipart = new MimeMultipart("alternative");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html");
        multipart.addBodyPart(htmlPart);

        message.setContent(multipart);
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject, "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        transport.connect();
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();
    } catch (Exception e) {
        LOG.debug("Exception while sending email: ", e);
        throw e;
    }
}

From source file:mb.MbTermin.java

private void posaljiMail(Student student, Profesor profesorId, Termin t) {

    //ToDo change username and password for google account
    final String username = "*****";
    final String password = "*****";

    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() {
        @Override//from   www .  j  av a 2  s.co  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(profesorId.getEmail()));
        message.setSubject("Konsultacije");
        message.setText("Potovani " + profesorId.getIme() + " " + profesorId.getPrezime() + ","
                + "\n\n Student " + student.getIme() + " " + student.getPrezime()
                + " je zakazao termin konsultacija" + " za datum " + t.getTerminPK().getVreme() + ".");
        Transport.send(message);

        System.out.println("Message sent");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.bizintelapps.cars.service.impl.EmailServiceImpl.java

/**
 * /*from  w ww .  j  a  va 2 s.  c om*/
 * @param recipients
 * @param subject
 * @param message
 * @param from
 * @throws MessagingException
 */
private void sendSSMessage(String recipients[], String subject, Car car, String comment) {

    try {
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            if (recipients[i] != null && recipients[i].length() > 0) {

                addressTo[i] = new InternetAddress(recipients[i]);

            }
        }

        if (addressTo == null || addressTo.length == 0) {
            return;
        }

        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SEND_FROM_USERNAME, SEND_FROM_PASSWORD);
            }
        });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(EMAIL_FROM_ADDRESS);
        msg.setFrom(addressFrom);
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        msg.setSubject(subject);
        String message = buildMessage(car, comment);
        msg.setContent(message, EMAIL_CONTENT_TYPE);

        Transport.send(msg);
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        throw new RuntimeException("Error sending email, please check to and from emails are correct!");
    }
}

From source file:com.github.sleroy.junit.mail.server.test.MailSender.java

/**
 * Send mail./* w ww.  j  a  v a 2s  .com*/
 *
 * @param from
 *            Sender's email ID needs to be mentioned
 * @param to
 *            Recipient's email ID needs to be mentioned.
 * @param subject
 *            the subject
 * @throws MessagingException
 */
public void sendMail(String from, String to, String subject, String body) throws MessagingException {

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.port", Integer.toString(port));

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    Transport transport = null;
    try {
        transport = session.getTransport();

        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

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

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

        // Now set the actual message
        message.setText(body);

        // Send message
        transport.send(message);
        System.out.println("Sent message successfully....");
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}

From source file:gov.nih.nci.protexpress.ui.actions.registration.EmailUtil.java

private static MimeMessage constructMessage(List<String> mailRecipients, String from, String mailSubject)
        throws MessagingException {
    Validate.notEmpty(mailRecipients, "No email recipients are specified");
    if (StringUtils.isEmpty(mailSubject)) {
        LOG.info("No email subject specified");
    }/*  ww  w . j  a v a2s.  co  m*/

    List<Address> addresses = new ArrayList<Address>();
    for (String recipient : mailRecipients) {
        addresses.add(new InternetAddress(recipient));
    }

    MimeMessage message = new MimeMessage(mailSession);
    message.setRecipients(Message.RecipientType.TO, addresses.toArray(new Address[addresses.size()]));
    message.setFrom(new InternetAddress(from));
    message.setSubject(mailSubject);

    return message;
}