Example usage for javax.mail.internet MimeMessage addRecipient

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

Introduction

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

Prototype

public void addRecipient(RecipientType type, Address address) throws MessagingException 

Source Link

Document

Add this recipient address to the existing ones of the given type.

Usage

From source file:quickforms.sme.UseFulMethods.java

static public void sendEmail(String d_email, String pwd, String m_to, String m_subject, String message)
        throws Exception {
    final String from = d_email;
    final String password = pwd;
    class SMTPAuthenticator extends Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, password);
        }/*from ww  w  .j a v a  2  s  .c om*/
    }

    //String d_uname = "email";
    //String d_password = "password";
    String d_host = "smtp.gmail.com";
    String d_port = "465"; //465,587

    Properties props = new Properties();
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.host", d_host);
    props.put("mail.smtp.port", d_port);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.socketFactory.port", d_port);
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SMTPAuthenticator auth = new SMTPAuthenticator();
    Session session = Session.getInstance(props, auth);
    session.setDebug(true);

    MimeMessage msg = new MimeMessage(session);

    //msg.setText(message);
    // Send the actual HTML message, as big as you like

    msg.setContent(message, "text/html");
    msg.setSubject(m_subject);
    msg.setFrom(new InternetAddress(from));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));

    Transport transport = session.getTransport("smtps");
    transport.connect(d_host, 465, from, password);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();

}

From source file:ru.org.linux.user.RegisterController.java

private static void sendEmail(Template tmpl, String nick, String email, boolean isNew)
        throws MessagingException {
    StringBuilder text = new StringBuilder();

    text.append("?!\n\n");
    if (isNew) {/*from   w  ww.j  a  va2  s .  c  om*/
        text.append(
                "\t   ? http://www.linux.org.ru/ ?? ?? ?,\n");
    } else {
        text.append(
                "\t   ? http://www.linux.org.ru/   ?? ?,\n");
    }

    text.append("     ? ? (e-mail).\n\n");
    text.append(
            "  ?    ? ? ?: '");
    text.append(nick);
    text.append("'\n\n");
    text.append(
            "?   ,     - ?  ? ?!\n\n");

    if (isNew) {
        text.append(
                "?     ???    ? http://www.linux.org.ru/,\n");
        text.append(
                "  ?  ? ?   ?    ?.\n\n");
    } else {
        text.append(
                "?      ? ? ? http://www.linux.org.ru/,\n");
        text.append("  ?  ? .\n\n");
    }

    String regcode = User.getActivationCode(tmpl.getSecret(), nick, email);

    text.append(
            "?    ?? http://www.linux.org.ru/activate.jsp\n\n");
    text.append(" : ").append(regcode).append("\n\n");
    text.append("  ?!\n");

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));

    emailMessage.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email));
    emailMessage.setSubject("Linux.org.ru registration");
    emailMessage.setSentDate(new Date());
    emailMessage.setText(text.toString(), "UTF-8");

    Transport.send(emailMessage);
}

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 w w  .  ja v  a 2s .  c  om*/
    });
    //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:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static MimeMessageHelper createEmailMessage(String from, String to)
        throws AddressException, MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(from));
    for (String recipient : to.split(";")) {
        email.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    }//  w w  w .  j  a  va 2 s .c o  m

    return new MimeMessageHelper(email);
}

From source file:com.email.SendEmailCalInvite.java

/**
 * Sends email based off of the section it comes from. This creates a
 * calendar invite object that is interactive by Outlook.
 *
 * @param eml EmailOutInviteModel/*from  w  w w .j  av a2s . c  om*/
 */
public static void sendCalendarInvite(EmailOutInvitesModel eml) {
    SystemEmailModel account = null;

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(eml.getSection())) {
            account = acc;
            break;
        }
    }
    if (account != null) {
        //Get parts
        String FromAddress = account.getEmailAddress();
        String[] TOAddressess = ((eml.getToAddress() == null) ? "".split(";") : eml.getToAddress().split(";"));
        String[] CCAddressess = ((eml.getCcAddress() == null) ? "".split(";") : eml.getCcAddress().split(";"));
        String emailSubject = "";
        BodyPart emailBody = body(eml);
        BodyPart inviteBody = null;

        if (eml.getHearingRoomAbv() == null) {
            emailSubject = eml.getEmailSubject() == null
                    ? (eml.getEmailBody() == null ? eml.getCaseNumber() : eml.getEmailBody())
                    : eml.getEmailSubject();
            inviteBody = responseDueCalObject(eml, account);
        } else {
            emailSubject = eml.getEmailSubject() == null ? Subject(eml) : eml.getEmailSubject();
            inviteBody = inviteCalObject(eml, account, emailSubject);
        }

        //Set Email Parts
        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);
        Session session = Session.getInstance(properties, auth);
        MimeMessage smessage = new MimeMessage(session);
        Multipart multipart = new MimeMultipart("alternative");
        try {
            smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
            for (String To : TOAddressess) {
                if (EmailValidator.getInstance().isValid(To)) {
                    smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                }
            }
            for (String Cc : CCAddressess) {
                if (EmailValidator.getInstance().isValid(Cc)) {
                    smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(Cc));
                }
            }
            smessage.setSubject(emailSubject);
            multipart.addBodyPart(emailBody);
            multipart.addBodyPart(inviteBody);
            smessage.setContent(multipart);
            if (Global.isOkToSendEmail()) {
                Transport.send(smessage);
            } else {
                Audit.addAuditEntry("Cal Invite Not Actually Sent: " + eml.getId() + " - " + emailSubject);
            }
            EmailOutInvites.deleteEmailEntry(eml.getId());
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    }
}

From source file:org.apache.usergrid.apm.service.util.Mailer.java

public static void send(String recipeintEmail, String subject, String messageText) {
    /*/* w  w  w.jav  a  2 s. c om*/
     * It is a good practice to put this in a java.util.Properties file and
     * encrypt password. Scroll down to comments below to see how to use
     * java.util.Properties in JSF context.
     */
    Properties props = new Properties();
    try {
        props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/email.properties"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    final String senderEmail = props.getProperty("mail.smtp.sender.email");
    final String smtpUser = props.getProperty("mail.smtp.user");
    final String senderName = props.getProperty("mail.smtp.sender.name");
    final String senderPassword = props.getProperty("senderPassword");
    final String emailtoCC = props.getProperty("instaopsOpsEmailtoCC");

    Session session = Session.getDefaultInstance(props, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUser, senderPassword);
        }
    });
    session.setDebug(false);

    try {
        MimeMessage message = new MimeMessage(session);

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(messageText, "text/html");

        // Add message text
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        message.setSubject(subject);
        InternetAddress senderAddress = new InternetAddress(senderEmail, senderName);
        message.setFrom(senderAddress);
        message.addRecipient(Message.RecipientType.CC, new InternetAddress(emailtoCC));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipeintEmail));
        Transport.send(message);
        log.info("email sent");
    } catch (MessagingException m) {
        log.error(m.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:at.gv.egovernment.moa.id.configuration.helper.MailHelper.java

private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content)
        throws ConfigurationException {
    try {/*from   w  w w .jav  a 2 s.c  o  m*/
        log.debug("Sending mail.");
        MiscUtil.assertNotNull(subject, "subject");
        MiscUtil.assertNotNull(recipient, "recipient");
        MiscUtil.assertNotNull(content, "content");

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", config.getSMTPMailHost());
        log.trace("Mail host: " + config.getSMTPMailHost());
        if (config.getSMTPMailPort() != null) {
            log.trace("Mail port: " + config.getSMTPMailPort());
            props.setProperty("mail.port", config.getSMTPMailPort());
        }
        if (config.getSMTPMailUsername() != null) {
            log.trace("Mail user: " + config.getSMTPMailUsername());
            props.setProperty("mail.user", config.getSMTPMailUsername());
        }
        if (config.getSMTPMailPassword() != null) {
            log.trace("Mail password: " + config.getSMTPMailPassword());
            props.setProperty("mail.password", config.getSMTPMailPassword());
        }

        Session mailSession = Session.getDefaultInstance(props, null);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject(subject);
        log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress());
        message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName()));
        log.trace("Recipient: " + recipient);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        log.trace("Creating multipart content of mail.");
        MimeMultipart multipart = new MimeMultipart("related");

        log.trace("Adding first part (html)");
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15");
        multipart.addBodyPart(messageBodyPart);

        //         log.trace("Adding mail images");
        //         messageBodyPart = new MimeBodyPart();
        //         for (Image image : images) {
        //            messageBodyPart.setDataHandler(new DataHandler(image));
        //            messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">");
        //            multipart.addBodyPart(messageBodyPart);
        //         }

        message.setContent(multipart);
        transport.connect();
        log.trace("Sending mail message.");
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        log.trace("Successfully sent.");
        transport.close();

    } catch (MessagingException e) {
        throw new ConfigurationException(e);

    } catch (UnsupportedEncodingException e) {
        throw new ConfigurationException(e);

    }
}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email.//  w ww.j a  va2  s  .c o m
 * @param bodyText Body text of the email.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmail(String to, String from, String subject, String bodyText)
        throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);
    email.setText(bodyText);
    return email;
}

From source file:javamailclient.GmailAPI.java

/**
 * Create a MimeMessage using the parameters provided.
 *
 * @param to Email address of the receiver.
 * @param from Email address of the sender, the mailbox account.
 * @param subject Subject of the email./*from w  w w.  j  a va2s. c  om*/
 * @param bodyText Body text of the email.
 * @param fileDir Path to the directory containing attachment.
 * @param filename Name of file to be attached.
 * @return MimeMessage to be used to send email.
 * @throws MessagingException
 */
public static MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText,
        String fileDir, String filename) throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);

    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(bodyText, "text/plain");
    mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(mimeBodyPart);

    mimeBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(fileDir + filename);

    mimeBodyPart.setDataHandler(new DataHandler(source));
    mimeBodyPart.setFileName(filename);
    String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename));
    mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
    mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

    multipart.addBodyPart(mimeBodyPart);

    email.setContent(multipart);

    return email;
}

From source file:network.thunder.server.etc.Tools.java

public static void emailException(Exception e, Message m, Channel c, Payment p, Transaction channelTransaction,
        Transaction t) {//from www. j  a va2  s .co m
    String to = "matsjj@gmail.com";
    String from = "exception@thunder.network";
    String host = "localhost";
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(properties);

    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));

        message.setSubject("New Critical Exception thrown..");

        String text = "";

        text += Tools.stacktraceToString(e);
        text += "\n";
        if (m != null) {
            text += m;
        }
        text += "\n";
        if (c != null) {
            text += c;
        }
        text += "\n";
        if (p != null) {
            text += p;
        }
        text += "\n";
        if (channelTransaction != null) {
            text += channelTransaction;
        }
        text += "\n";
        if (t != null) {
            text += t;
        }

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

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        //           mex.printStackTrace();
    }
}