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.netflix.genie.server.jobmanager.impl.JobMonitor.java

/**
 * Check the properties file to figure out if an email
 * needs to be sent at the end of the job. If yes, get
 * mail properties and try and send email about Job Status.
 * @return 0 for success, -1 for failure
 *///from   ww w .ja v  a  2s.  c  o m
private boolean sendEmail(String emailTo) {
    logger.debug("called");

    if (!config.getBoolean("netflix.genie.server.mail.enable", false)) {
        logger.warn("Email is disabled but user has specified an email address.");
        return false;
    }

    // Sender's email ID
    String fromEmail = config.getString("netflix.genie.server.mail.smpt.from", "no-reply-genie@geniehost.com");
    logger.info("From email address to use to send email: " + fromEmail);

    // Set the smtp server hostname. Use localhost as default
    String smtpHost = config.getString("netflix.genie.server.mail.smtp.host", "localhost");
    logger.debug("Email smtp server: " + smtpHost);

    // Get system properties
    Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    // check whether authentication should be turned on
    Authenticator auth = null;

    if (config.getBoolean("netflix.genie.server.mail.smtp.auth", false)) {
        logger.debug("Email Authentication Enabled");

        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");

        String userName = config.getString("netflix.genie.server.mail.smtp.user");
        String password = config.getString("netflix.genie.server.mail.smtp.password");

        if ((userName == null) || (password == null)) {
            logger.error("Authentication is enabled and username/password for smtp server is null");
            return false;
        }
        logger.debug(
                "Constructing authenticator object with username" + userName + " and password " + password);
        auth = new SMTPAuthenticator(userName, password);
    } else {
        logger.debug("Email authentication not enabled.");
    }

    // Get the default Session object.
    Session session = Session.getInstance(properties, auth);

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

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

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

        // Set Subject: header field
        message.setSubject("Genie Job " + ji.getJobName() + " completed with Status: " + ji.getStatus());

        // Now set the actual message
        String body = "Your Genie Job is complete\n\n" + "Job ID: " + ji.getJobID() + "\n" + "Job Name: "
                + ji.getJobName() + "\n" + "Status: " + ji.getStatus() + "\n" + "Status Message: "
                + ji.getStatusMsg() + "\n" + "Output Base URL: " + ji.getOutputURI() + "\n";

        message.setText(body);

        // Send message
        Transport.send(message);
        logger.info("Sent email message successfully....");
        return true;
    } catch (MessagingException mex) {
        logger.error("Got exception while sending email", mex);
        return false;
    }
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message//ww  w . j  av a  2s .c o m
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:mx.uatx.tesis.managebeans.IndexMB.java

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {
    try {// w ww.  jav a 2  s . c o m
        // Propiedades de la conexin
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com");
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);

        // Construimos el mensaje
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("alfons018pbg@gmail.com"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + ""));
        message.setSubject("Asistencia tcnica");
        message.setText("\n \n \n Estimado:  " + nombre + "  " + apellido
                + "\n El Servicio Tecnico de SEA ta da la bienvenida. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + password2 + "");

        // Lo enviamos.
        Transport t = session.getTransport("smtp");
        t.connect("alfons018pbg@gmail.com", "al12fo05zo1990");
        t.sendMessage(message, message.getAllRecipients());

        // Cierre.
        t.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarRequestResetPasswordHtml.java

protected void sendPasswordResetEMail(HttpServletRequest request, ICFAstSecUserObj resetUser,
        ICFAstClusterObj cluster) throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAst22SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpEmailFrom");
    }//from w w w.ja  v  a2s .co m

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAst22SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAst22SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "JNDI lookup for CFAst22SmtpPassword");
    }

    Session emailSess = Session.getInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUsername, smtpPassword);
        }
    });

    String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n"
            + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress()
            + " used for accessing " + clusterDescription + ".\n" + "<p>"
            + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI
            + "/CFAstSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
}

From source file:com.project.implementation.ReservationImplementation.java

public String makeReservation(GuestDTO guestDTO, Integer no_of_rooms_Int, Date checkin_date,
        Date checkout_date) {//from w w  w.ja  v  a 2 s  .  c om
    Integer guestID = 0, guestCount;
    String room_selected = guestDTO.getRoom_no_selected();
    Guest guestObject = new Guest();

    try {
        org.apache.commons.beanutils.BeanUtils.copyProperties(guestObject, guestDTO);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

    //check email id if exist
    guestID = guestDAO.checkGuestExist(guestDTO.getGuest_email(), guestDTO.getLicense_no());
    System.out.println("guestID: " + guestID);
    //if email id, license exist
    if (!(guestID == 0)) {
        System.out.println("value = ");
        //update details
        guestCount = guestDAO.updateUserDetails(guestID, guestDTO.getGuest_name(), guestDTO.getStreet(),
                guestDTO.getCity(), guestDTO.getState(), guestDTO.getZip());
        if (guestCount != 0)
            guestObject = guestDAO.getGuestRecord(guestID);
    } else {
        guestObject = guestDAO.save(guestObject);
    }

    String randomDate = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis());

    UUID id = UUID.randomUUID();
    String token_no = String.valueOf(id);
    //System.out.println(sensor_id);

    // String token_no = guestObject.getLicense_no() + guestObject.getGuest_id()+randomDate;

    java.util.Date todayUtilDate = Calendar.getInstance().getTime();//2015-12-05
    java.sql.Date todaySqlDate = new java.sql.Date(todayUtilDate.getTime());

    Reservation reservationObject = new Reservation();
    //        reservationObject.setReservation_id(0);
    reservationObject.setGuest_id(guestObject.getGuest_id());
    reservationObject.setReservation_token(token_no);
    reservationObject.setReservation_date(todaySqlDate);
    reservationObject.setReservation_status(ReservationStatus.R);
    reservationObject = reservationDAO.save(reservationObject);
    // Integer reservation_id = reservationObject.getReservation_id();

    String[] resultStringArray = guestDTO.getRoom_no_selected().split(",");
    ArrayList<Integer> arrRooms = new ArrayList<Integer>();
    for (String str : resultStringArray) {
        arrRooms.add(Integer.parseInt(str));
        CheckinRoomMapping checkinRoomMappingObject = new CheckinRoomMapping();
        checkinRoomMappingObject.setReservation(reservationObject);
        checkinRoomMappingObject.setRoom_no(Integer.parseInt(str));
        checkinRoomMappingObject.setCheckin_date(checkin_date);
        checkinRoomMappingObject.setCheckout_date(checkout_date);
        checkinRoomMappingObject.setGuest_count(0);
        checkinRoomMappingObject.setMappingId(0);
        checkinRoomMappingDAO.save(checkinRoomMappingObject);
    }
    //add email code start here

    final String from = "express.minihotel@gmail.com";
    String to = guestObject.getGuest_email();
    String body = "Hello " + guestObject.getGuest_name()
            + ", <br/><br></br>Your reservation has been confirmed.Your reservation ID is <font color='red'><b>"
            + token_no
            + "</b></font>.</br>Please bring the Driving License for verification at the time of Check In.</br><br></br>"
            + "<b>Note:</b>If you want to cancel the reservation, "
            + "please <a href=\'http://52.53.255.195:8080/CmpE275Team07Fall2015TermProject/v1/cancelReservation?reservation_token="
            + token_no + "\'>Click Here</a><br></br>--<i>Express Hotel</i>";
    String subject = "Express Hotel Reservation Confirmation <" + token_no + ">";

    final String password = "Minihotel@2015";
    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() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, password);
        }
    });
    try {
        MimeMessage email = new MimeMessage(session);
        email.setFrom(new InternetAddress(from));
        email.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
        email.setSubject(subject);
        email.setContent(body, "text/html");
        Transport.send(email);

    } catch (MessagingException e) {

        throw new RuntimeException(e);

    }
    //email code end here

    return token_no;
}

From source file:com.netflix.genie.server.jobmanager.impl.JobMonitorImpl.java

/**
 * Check the properties file to figure out if an email needs to be sent at
 * the end of the job. If yes, get mail properties and try and send email
 * about Job Status./*www.  jav  a  2s  .com*/
 *
 * @return 0 for success, -1 for failure
 * @throws GenieException on issue
 */
private boolean sendEmail(final String emailTo, final boolean killed) throws GenieException {
    LOG.debug("called");
    final Job job = this.jobService.getJob(this.jobId);

    if (!this.config.getBoolean("com.netflix.genie.server.mail.enable", false)) {
        LOG.warn("Email is disabled but user has specified an email address.");
        return false;
    }

    // Sender's email ID
    final String fromEmail = this.config.getString("com.netflix.genie.server.mail.smpt.from",
            "no-reply-genie@geniehost.com");
    LOG.info("From email address to use to send email: " + fromEmail);

    // Set the smtp server hostname. Use localhost as default
    final String smtpHost = this.config.getString("com.netflix.genie.server.mail.smtp.host", "localhost");
    LOG.debug("Email smtp server: " + smtpHost);

    // Get system properties
    final Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", smtpHost);

    // check whether authentication should be turned on
    Authenticator auth = null;

    if (this.config.getBoolean("com.netflix.genie.server.mail.smtp.auth", false)) {
        LOG.debug("Email Authentication Enabled");

        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.auth", "true");

        final String userName = config.getString("com.netflix.genie.server.mail.smtp.user");
        final String password = config.getString("com.netflix.genie.server.mail.smtp.password");

        if (userName == null || password == null) {
            LOG.error("Authentication is enabled and username/password for smtp server is null");
            return false;
        }
        LOG.debug("Constructing authenticator object with username" + userName + " and password " + password);
        auth = new SMTPAuthenticator(userName, password);
    } else {
        LOG.debug("Email authentication not enabled.");
    }

    // Get the default Session object.
    final Session session = Session.getInstance(properties, auth);

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

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

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

        JobStatus jobStatus;

        if (killed) {
            jobStatus = JobStatus.KILLED;
        } else {
            jobStatus = job.getStatus();
        }

        // Set Subject: header field
        message.setSubject("Genie Job " + job.getName() + " completed with Status: " + jobStatus);

        // Now set the actual message
        final String body = "Your Genie Job is complete\n\n" + "Job ID: " + job.getId() + "\n" + "Job Name: "
                + job.getName() + "\n" + "Status: " + job.getStatus() + "\n" + "Status Message: "
                + job.getStatusMsg() + "\n" + "Output Base URL: " + job.getOutputURI() + "\n";

        message.setText(body);

        // Send message
        Transport.send(message);
        LOG.info("Sent email message successfully....");
        return true;
    } catch (final MessagingException mex) {
        LOG.error("Got exception while sending email", mex);
        return false;
    }
}

From source file:net.fenyo.mail4hotspot.service.MailManager.java

public void sendMessage(Address from_addr, Address[] to_addr, Address[] cc_addr, String subject, String content)
        throws MessagingException {
    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(from_addr);
    msg.setRecipients(Message.RecipientType.TO, to_addr);
    if (cc_addr.length > 0)
        msg.setRecipients(Message.RecipientType.CC, cc_addr);
    msg.setSubject(subject, "UTF-8");
    msg.setContent(content, "text/plain");

    transport.sendMessage(msg, ArrayUtils.addAll(to_addr, cc_addr));
}

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testNullDatePasswordSet() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/* w  w w  .j a v  a2 s .  co  m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test6@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(1, result.size());
}

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testNegativeValidityInterval() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);/*from w  ww.  j a  v  a  2  s  .c  o  m*/

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test7@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(1, result.size());
}

From source file:mitm.application.djigzo.james.matchers.HasValidPasswordTest.java

@Test
public void testZeroValidityInterval() throws MessagingException, EncryptorException {
    HasValidPassword matcher = new HasValidPassword();

    MockMatcherConfig matcherConfig = new MockMatcherConfig("test", "matchOnError=false", mailetContext);

    matcher.init(matcherConfig);//from   w w w .jav a 2 s . c om

    Mail mail = new MockMail();

    MimeMessage message = new MimeMessage(MailSession.getDefaultSession());

    message.setContent("test", "text/plain");
    message.setFrom(new InternetAddress("123456@example.com"));

    message.saveChanges();

    mail.setMessage(message);

    Collection<MailAddress> recipients = new LinkedList<MailAddress>();

    recipients.add(new MailAddress("test1@example.com"));

    mail.setRecipients(recipients);

    Collection<?> result = matcher.match(mail);

    assertEquals(0, result.size());
}