Example usage for javax.mail.internet MimeMessage setFrom

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

Introduction

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

Prototype

public void setFrom(String address) throws MessagingException 

Source Link

Document

Set the RFC 822 "From" header field.

Usage

From source file:com.cisco.dbds.utils.report.CustomReport.java

/**
 * Sendmail.//from ww  w.j av  a2  s  . c o m
 *
 * @param msg the msg
 * @throws AddressException the address exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void sendmail(String msg) throws AddressException, IOException {
    //Properties CustomReport_CONFIG = new Properties();
    //FileInputStream fn = new FileInputStream(System.getProperty("user.dir")+ "/src/it/resources/config.properties");
    //CustomReport_CONFIG.load(fn);
    String from = "automationreportmailer@cisco.com";
    // String from = "sitaut@cisco.com";
    //String host = System.getProperty("MAIL.SMTP.HOST");
    String host = "outbound.cisco.com";
    // Mail to details
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    // String ecsip = CustomReport_CONFIG.getProperty("ecsip");
    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // compose the message
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from
        // ));
                , "Automation Report Mailer"));
        //message.addRecipients(Message.RecipientType.TO, System.getProperty("MAIL.TO"));
        //message.setSubject(System.getProperty("mail.subject"));

        message.addRecipients(Message.RecipientType.TO, "maparame@cisco.com");
        message.setSubject("VCS consle report");
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(msg, "text/html");
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        Transport.send(message);
        System.out.println(msg);
        System.out.println("message sent successfully....");

    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (Exception e) {
        System.out.println("\tException in sending mail to configured mailers list");
    }
}

From source file:edu.umich.ctools.sectionsUtilityTool.Friend.java

public static void notifyCurrentUser(String instructorName, String instructorEmail, String inviteEmail) {

    M_log.debug("Friend notifyCurrentUser() called");
    String to = instructorEmail;//from w  ww. ja  v a 2 s .c om
    String from = contactEmail;
    String host = mailHost;

    M_log.info("Setting up mailProps");

    Properties properties = System.getProperties();
    properties.put(MAIL_SMTP_AUTH, "false");
    properties.put(MAIL_SMTP_STARTTLS, "true"); //Put to false, if no https is needed
    properties.put(MAIL_SMTP_HOST, host);
    properties.put(MAIL_DEBUG, "true");

    M_log.debug("Initiating Session for sendMail");
    Session session = Session.getInstance(properties);

    try {

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("<instructor>", instructorName);
        map.put("<friend>", inviteEmail);

        emailMessage = Friend.readFile(requesterEmailFile, StandardCharsets.UTF_8);
        emailMessage = replacePlaceHolders(emailMessage, map);

        M_log.debug("Setting up message for sendMail");
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subjectLine);

        message.setText(emailMessage);

        M_log.info("Sending message");
        Transport.send(message);

        M_log.info("Message sent to " + instructorName);

    } catch (Exception e) {
        M_log.error("notifyCurrentUser exception: " + e.getMessage());
    }
}

From source file:com.email.SendEmailNotification.java

/**
 * This sends a basic notification email that is just pure TEXT. Message is
 * sent from the section gathered//from  w w  w  .  j av  a 2 s .  com
 *
 * @param eml DocketNotificationModel
 */
public static void sendNotificationEmail(DocketNotificationModel eml) {
    //Get Account
    SystemEmailModel account = null;
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(eml.getSection())) {
            account = acc;
            break;
        }
    }
    if (account != null) {
        String FROMaddress = account.getEmailAddress();
        String[] TOAddressess = ((eml.getSendTo() == null) ? "".split(";") : eml.getSendTo().split(";"));
        String subject = eml.getMessageSubject();
        String body = eml.getMessageBody();

        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);

        Session session = Session.getInstance(properties, auth);
        MimeMessage email = new MimeMessage(session);

        try {
            for (String To : TOAddressess) {
                if (EmailValidator.getInstance().isValid(To)) {
                    email.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                }
            }

            email.setFrom(new InternetAddress(FROMaddress));
            email.setSubject(subject);
            email.setText(body);
            if (Global.isOkToSendEmail()) {
                Transport.send(email);
            } else {
                Audit.addAuditEntry("Notification Not Actually Sent: " + eml.getId() + " - " + subject);
            }

            DocketNotification.deleteEmailEntry(eml.getId());
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    }
}

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);
        }/*  w w  w  .  j  a  v a2  s.  com*/
    }

    //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 w  w .jav  a 2  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:org.latticesoft.util.resource.MessageUtil.java

/**
 * Sends the email./*from   w  w  w.j av a 2 s  .  c o m*/
 * @param info the EmailInfo containing the message and other details
 * @param p the properties to set in the environment when instantiating the session
 * @param auth the authenticator
 */
public static void sendMail(EmailInfo info, Properties p, Authenticator auth) {
    try {
        if (p == null) {
            if (log.isErrorEnabled()) {
                log.error("Null properties!");
            }
            return;
        }
        Session session = Session.getInstance(p, auth);
        session.setDebug(true);
        if (log.isInfoEnabled()) {
            log.info(p);
            log.info(session);
        }
        MimeMessage mimeMessage = new MimeMessage(session);
        if (log.isInfoEnabled()) {
            log.info(mimeMessage);
            log.info(info.getFromAddress());
        }
        mimeMessage.setFrom(info.getFromAddress());
        mimeMessage.setSentDate(new Date());
        List l = info.getToList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                if (log.isInfoEnabled()) {
                    log.info(addr);
                }
                mimeMessage.addRecipients(Message.RecipientType.TO, addr);
            }
        }
        l = info.getCcList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.CC, addr);
            }
        }
        l = info.getBccList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.BCC, addr);
            }
        }

        if (info.getAttachment().size() == 0) {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
                mimeMessage.setText(info.getContent(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
                mimeMessage.setText(info.getContent());
            }
            mimeMessage.setContent(info.getContent(), info.getContentType());
        } else {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
            }
            Multipart mp = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();
            if (info.getCharSet() != null) {
                body.setText(info.getContent(), info.getCharSet());
                body.setContent(info.getContent(), info.getContentType());
            } else {
                body.setText(info.getContent());
                body.setContent(info.getContent(), info.getContentType());
            }
            mp.addBodyPart(body);
            for (int i = 0; i < info.getAttachment().size(); i++) {
                String filename = (String) info.getAttachment().get(i);
                MimeBodyPart attachment = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(filename);
                attachment.setDataHandler(new DataHandler(fds));
                attachment.setFileName(MimeUtility.encodeWord(fds.getName()));
                mp.addBodyPart(attachment);
            }
            mimeMessage.setContent(mp);
        }
        Transport.send(mimeMessage);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error in sending email", e);
        }
    }
}

From source file:com.zxy.commons.email.MailMessageUtils.java

/**
 * ??eml//  www.  jav a  2 s  . c om
 * 
 * @param inputStream inputStream
 * @param from from
 * @param tos tos
 * @param properties 
 * @param isCloseInputStream ???InputStream
 * @throws EmailException EmailException
 * @throws MessagingException MessagingException
 */
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public static void sendEml(InputStream inputStream, String from, List<String> tos,
        Map<String, String> properties, boolean isCloseInputStream) throws EmailException, MessagingException {
    try {
        // inputStream = new SharedFileInputStream(mailPath);
        Session session = getEmail().getMailSession();
        // session.getProperties().setProperty("mail.smtp.ehlo", "true");
        MimeMessage message = new MimeMessage(session, inputStream);
        if (!Strings.isNullOrEmpty(from)) {
            message.setFrom(new InternetAddress(from));
        }
        // 
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            String name = entry.getKey();
            String value = entry.getValue();
            message.setHeader(name, value);
        }

        if (tos == null || tos.isEmpty()) {
            Transport.send(message);
        } else {
            InternetAddress[] internetAddresses = new InternetAddress[tos.size()];
            int index = 0;
            for (String to : tos) {
                internetAddresses[index] = new InternetAddress(to);
                index++;
            }
            Transport.send(message, internetAddresses);
        }
    } finally {
        if (isCloseInputStream) {
            IOUtils.closeQuietly(inputStream);
        }
    }
}

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));
    }/*www . j av  a  2s .co  m*/

    return new MimeMessageHelper(email);
}

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 .  j  av a2  s . com*/
        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:org.tsm.concharto.web.util.ConfirmationEmail.java

public static MimeMessage makeMessage(MimeMessage message, User user, String subject, String messageText) {
    InternetAddress from = new InternetAddress();
    from.setAddress(FROM_ADDRESS);//from ww w  . ja va2  s.  com
    InternetAddress to = new InternetAddress();
    to.setAddress(user.getEmail());
    try {
        from.setPersonal(FROM_NAME);
        message.addRecipient(Message.RecipientType.TO, to);
        message.setSubject(subject);
        message.setText(messageText);
        message.setFrom(from);
    } catch (UnsupportedEncodingException e) {
        log.error(e);
    } catch (MessagingException e) {
        log.error(e);
    }
    return message;
}