Example usage for javax.mail Message setFrom

List of usage examples for javax.mail Message setFrom

Introduction

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

Prototype

public abstract void setFrom(Address address) throws MessagingException;

Source Link

Document

Set the "From" attribute in this Message.

Usage

From source file:com.spartasystems.holdmail.smtp.OutgoingMailSender.java

public void redirectMessage(String recipient, String rawBody) {

    // TODO: this is a crude first pass at bouncing a mail and probably needs to be a little more sophisticated

    try {/*from w ww. j a  v  a2s.  c om*/

        Session session = getMailSession();
        Message message = initializeMimeMessage(rawBody, session);

        // wipe out ALL exisitng recipients
        message.setRecipients(Message.RecipientType.TO, new Address[] {});
        message.setRecipients(Message.RecipientType.CC, new Address[] {});
        message.setRecipients(Message.RecipientType.BCC, new Address[] {});

        // and set the new recipient
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));

        InternetAddress[] parsedFrom = InternetAddress.parse(getSenderFrom());
        if (parsedFrom.length > 0) {
            message.setFrom(parsedFrom[0]);
            logger.info("Outgoing mail will have From: " + parsedFrom[0].getAddress());
        }

        sendMessage(message);

        logger.info("Outgoing mail forwarded to " + recipient);

    } catch (MessagingException e) {
        throw new HoldMailException("couldn't send mail: " + e.getMessage(), e);
    }

}

From source file:Mailer.java

/** Send the message.
 *//*from www . ja v  a 2  s  .  com*/
public synchronized void doSend() throws MessagingException {

    if (!isComplete())
        throw new IllegalArgumentException("doSend called before message was complete");

    /** Properties object used to pass props into the MAIL API */
    Properties props = new Properties();
    props.put("mail.smtp.host", mailHost);

    // Create the Session object
    if (session == null) {
        session = Session.getDefaultInstance(props, null);
        if (verbose)
            session.setDebug(true); // Verbose!
    }

    // create a message
    final Message mesg = new MimeMessage(session);

    InternetAddress[] addresses;

    // TO Address list
    addresses = new InternetAddress[toList.size()];
    for (int i = 0; i < addresses.length; i++)
        addresses[i] = new InternetAddress((String) toList.get(i));
    mesg.setRecipients(Message.RecipientType.TO, addresses);

    // From Address
    mesg.setFrom(new InternetAddress(from));

    // CC Address list
    addresses = new InternetAddress[ccList.size()];
    for (int i = 0; i < addresses.length; i++)
        addresses[i] = new InternetAddress((String) ccList.get(i));
    mesg.setRecipients(Message.RecipientType.CC, addresses);

    // BCC Address list
    addresses = new InternetAddress[bccList.size()];
    for (int i = 0; i < addresses.length; i++)
        addresses[i] = new InternetAddress((String) bccList.get(i));
    mesg.setRecipients(Message.RecipientType.BCC, addresses);

    // The Subject
    mesg.setSubject(subject);

    // Now the message body.
    mesg.setText(body);

    // Finally, send the message! (use static Transport method)
    // Do this in a Thread as it sometimes is too slow for JServ
    // new Thread() {
    // public void run() {
    // try {

    Transport.send(mesg);

    // } catch (MessagingException e) {
    // throw new IllegalArgumentException(
    // "Transport.send() threw: " + e.toString());
    // }
    // }
    // }.start();
}

From source file:com.enonic.vertical.userservices.OrderHandlerController.java

private void sendMail(String receiverEmail, String receiverName, String senderEmail, String senderName,
        String subject, String message) throws MessagingException, UnsupportedEncodingException {

    // smtp server
    Properties smtpProperties = new Properties();
    smtpProperties.put("mail.smtp.host", verticalProperties.getMailSmtpHost());
    Session session = Session.getDefaultInstance(smtpProperties, null);

    // create message
    Message msg = new MimeMessage(session);

    // set from address
    if (senderEmail != null && !senderEmail.equals("")) {
        InternetAddress addressFrom = new InternetAddress(senderEmail);
        if (senderName != null && !senderName.equals("")) {
            addressFrom.setPersonal(senderName);
        }/*from   w ww  . j  av a  2s  . c  o m*/
        msg.setFrom(addressFrom);
    }

    // set to address
    InternetAddress addressTo = new InternetAddress(receiverEmail);
    if (receiverName != null) {
        addressTo.setPersonal(receiverName);
    }
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    // Setting subject and content type
    msg.setSubject(subject);

    message = RegexpUtil.substituteAll("(\\\\n)", "\n", message);
    msg.setContent(message, "text/plain; charset=UTF-8");

    // send message
    Transport.send(msg);
}

From source file:Interface.FoodDistributionWorkArea.FoodDistributionWorkArea.java

public void sendEmail(String emailID, Food food) {

    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    final String username = "kunal.deora@gmail.com";//
    final String password = "adrika46";
    String text = "Hi Sir/Mam, " + '\n'
            + "You have received rewards points for the food you have donated. Details are listed below: "
            + '\n' + "Food Name:  " + food.getFoodName() + '\n' + "Food ID :" + food.getFoodBarCode() + '\n'
            + "Food Reward Points " + food.getRewardPoints() + '\n'
            + "If you have any queries you can contact us on +133333333333" + '\n'
            + "Thank you for helping for the betterment of society. Every little bite counts :) " + '\n';
    try {//  w  w w  .jav a2 s. c  o  m
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(username, password);
            }
        });

        // -- Create a new message --
        javax.mail.Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress("kunal.deora@gmail.com"));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(emailID, false));
        msg.setSubject("Congratulations! You have received reward points !!!");
        msg.setText(text);
        msg.setSentDate(new Date());
        javax.mail.Transport.send(msg);
        System.out.println("Message sent.");
    } catch (javax.mail.MessagingException e) {
        System.out.println("Erreur d'envoi, cause: " + e);
    }

}

From source file:org.springfield.lou.application.types.EuscreenxlitemApplication.java

public void sendContentProviderMail(Screen s, String data) {
    //System.out.println("Send mail to CP: " + data);

    JSONObject form = (JSONObject) JSONValue.parse(data);

    String mailfrom = "euscreen-portal@noterik.nl";
    String mailsubject = "Somebody showed interest in your item on EUScreen";
    String email = (String) form.get("email");
    String id = (String) form.get("identifier");
    String provider = (String) form.get("provider");
    String subject = (String) form.get("subject");
    String title = (String) form.get("title");
    String message = (String) form.get("message");
    message = message.replaceAll("(\r\n|\n)", "<br />");

    //Form validation
    JSONObject mailResponse = new JSONObject();
    Set<String> keys = form.keySet();
    boolean errors = false;
    for (String key : keys) {
        String value = (String) form.get(key);
        if (value == null || value.isEmpty()) {
            errors = true;//from w  w  w  .jav  a  2 s  .  co m
            break;
        }
    }

    if (errors) {
        mailResponse.put("status", "false");
        mailResponse.put("message", "Please fill in all the fields.");
        s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")");
        return;
    }

    String toemail = null;
    //Find the provider email
    FsNode providerNode = Fs.getNode("/domain/euscreenxl/user/" + provider + "/account/default");
    toemail = providerNode.getProperty("email");

    String body = "Identifier: " + id + "<br/>";
    body += "Title: " + title + "<br/>";
    body += "Link to item on EUScreen:<br/>";
    body += "<a href=\"http://euscreen.eu/item.html?id=" + id + "\">http://euscreen.eu/item.html?id=" + id
            + "</a><br/>";
    body += "-------------------------------------------<br/><br/>";
    body += "Subject: " + subject + "<br/>";
    body += "Message:<br/>";
    body += message + "<br/><br/>";
    body += "-------------------------------------------<br/>";
    body += "You can contact the sender of this message on: <a href=\"mailto:" + email + "\">" + email
            + "</a><br/>";

    if (this.inDevelMode()) { //In devel mode always send the email to the one filled in the form
        toemail = email;
    }

    //!!! Hack to send the email to the one filled in the form (for testing purposes). When on production it should be removed
    //toemail = email;

    boolean success = true;
    if (toemail != null) {
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            Session session = (Session) envCtx.lookup("mail/Session");

            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(mailfrom));
            InternetAddress to[] = new InternetAddress[1];
            to[0] = new InternetAddress(toemail);
            msg.setRecipients(Message.RecipientType.TO, to);

            InternetAddress bcc[] = new InternetAddress[1];
            bcc[0] = new InternetAddress("r.rozendal@noterik.nl");
            msg.setRecipients(Message.RecipientType.BCC, bcc);

            msg.setSubject(mailsubject);
            msg.setContent(body, "text/html");
            Transport.send(msg);
        } catch (Exception e) {
            System.out.println("Failed sending email: " + e);
            success = false;
        }
    } else {
        success = false;
    }

    String response = "Your message has been successfuly sent.";
    if (!success)
        response = "There was a problem sending your mail.<br/>Please try again later.";

    mailResponse.put("status", Boolean.toString(success));
    mailResponse.put("message", response);

    s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")");

}

From source file:org.kite9.diagram.server.AbstractKite9Controller.java

public void sendErrorEmail(Throwable t, String xml, String url) {
    try {/*from w  w  w .  ja  va2s.co  m*/
        Properties props = new Properties();
        props.put("mail.smtp.host", "server.kite9.org");
        Session session = Session.getInstance(props);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("servicetest@kite9.com"));
        msg.setRecipient(RecipientType.TO, new InternetAddress("rob@kite9.com"));
        String name = ctx.getServletContextName();
        boolean local = isLocal();
        msg.setSubject("Failure in " + (local ? "TEST" : name) + " Service: " + this.getClass().getName());
        StringWriter sw = new StringWriter(10000);
        PrintWriter pw = new PrintWriter(sw);
        pw.write("URL: " + url + "\n");

        t.printStackTrace(pw);

        if (xml != null) {
            pw.println();
            pw.print(xml);
        }

        pw.close();
        msg.setText(sw.toString());
        Transport.send(msg);
    } catch (Exception e) {
    } finally {
        t.printStackTrace();
    }
}

From source file:uk.ac.cam.cl.dtg.util.Mailer.java

/**
 * @param recipient//w ww  .ja  v  a 2s  .  c  o  m
 *            - string array of recipients that the message should be sent to
 * @param from
 *            - the e-mail address that should be used as the sending address
 * @param replyTo
 *            - the e-mail address that should be used as the reply-to address
 * @param subject
 *            - The message subject
 * @return a newly created message with all of the headers populated.
 * @throws MessagingException - if there is an error in setting up the message
 */
private Message setupMessage(final String[] recipient, final String from, @Nullable final String replyTo,
        @Nullable final String replyToName, final String subject)
        throws MessagingException, UnsupportedEncodingException {
    Validate.notEmpty(recipient);
    Validate.notBlank(recipient[0]);
    Validate.notBlank(from);

    Properties p = new Properties();
    p.put("mail.smtp.host", smtpAddress);

    if (null != smtpPort) {
        p.put("mail.smtp.port", smtpPort);
    }

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

    Session s = Session.getDefaultInstance(p);
    Message msg = new MimeMessage(s);

    InternetAddress sentBy = null;
    InternetAddress[] sender = new InternetAddress[1];
    InternetAddress[] recievers = new InternetAddress[recipient.length];

    sentBy = new InternetAddress(mailAddress, mailName);
    sender[0] = new InternetAddress(from);
    for (int i = 0; i < recipient.length; i++) {
        recievers[i] = new InternetAddress(recipient[i]);
    }

    if (sentBy != null && sender != null && recievers != null) {
        msg.setFrom(sentBy);
        msg.setRecipients(RecipientType.TO, recievers);
        msg.setSubject(subject);

        if (null != replyTo && null != replyToName) {
            msg.setReplyTo(new InternetAddress[] { new InternetAddress(replyTo, replyToName) });
        }
    }
    return msg;
}

From source file:EmailJndiServlet.java

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

    Message mailMsg = null;

    synchronized (mailSession) {

        mailMsg = new MimeMessage(mailSession);//a new email message
    }/*from   w w  w  .  ja v a  2  s . c  o m*/

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

public void sendMessage() throws Exception {

    Properties properties = System.getProperties();

    //populate the 'Properties' object with the mail
    //server address, so that the default 'Session'
    //instance can use it.
    properties.put("mail.smtp.host", smtpHost);

    Session session = Session.getDefaultInstance(properties);

    Message mailMsg = new MimeMessage(session);//a new email message

    InternetAddress[] addresses = null;//from  ww w.j  a va  2 s  .co  m

    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));

        } else {

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

        }

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

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

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

    } catch (Exception exc) {

        throw exc;

    }

}

From source file:UserInfo_Frame.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    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");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("anhduc.nguyen77000@gmail.com", "Matmachung020587");
        }//from   w w w  . java  2s .c o  m
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("anhduc.nguyen77000@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("oracle.submit@gmail.com"));
        message.setSubject("hi this is me");
        message.setText("hi how are you, i am fine");
        Transport.send(message);
        JOptionPane.showMessageDialog(null, "message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}