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

public static void main(String args[]) throws Exception {
    if (args.length != 3) {
        System.err.println("Usage: java MailExample host from to");
        System.exit(-1);//from   w w  w.java2  s . c o  m
    }

    String host = args[0];
    String from = args[1];
    String to = args[2];

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

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

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Define message
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject("The Subject");
    message.setText("The Message");

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

From source file:MainClass.java

public static void main(String[] args) {
    if (args.length != 4) {
        System.out.println("usage: java msgmultisend <to> <from> <smtp> true|false");
        return;/*  w  w  w.  j  a v a  2 s .  c  om*/
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Multipart Test");
        msg.setSentDate(new Date());

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create and fill the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // Use setText(text, charset), to show it off !
        mbp2.setText(msgText2, "us-ascii");

        // create the Multipart and its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // send the message
        Transport.send(msg);
    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:sendfile.java

public static void main(String[] args) {
    if (args.length != 5) {
        System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
        System.exit(1);/*from w w  w  .  j ava 2 s  .  c o m*/
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    String filename = args[3];
    boolean debug = Boolean.valueOf(args[4]).booleanValue();
    String msgText1 = "Sending a file.\n";
    String subject = "Sending a file";

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // set the Date: header
        msg.setSentDate(new Date());

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

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:msgsendsample.java

public static void main(String[] args) {
    if (args.length != 4) {
        usage();/*from   w ww.  j av  a 2 s  . c o m*/
        System.exit(1);
    }

    System.out.println();

    String to = args[0];
    String from = args[1];
    String host = args[2];
    boolean debug = Boolean.valueOf(args[3]).booleanValue();

    // create some properties and get the default Session
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    if (debug)
        props.put("mail.debug", args[3]);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail APIs Test");
        msg.setSentDate(new Date());
        // If the desired charset is known, you can use
        // setText(text, charset)
        msg.setText(msgText);

        Transport.send(msg);
    } catch (MessagingException mex) {
        System.out.println("\n--Exception handling in msgsendsample.java");

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++)
                        System.out.println("         " + invalid[i]);
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++)
                        System.out.println("         " + validUnsent[i]);
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++)
                        System.out.println("         " + validSent[i]);
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    }
}

From source file:sendfile.java

public static void main(String[] args) {
    if (args.length != 5) {
        System.out.println("usage: java sendfile <to> <from> <smtp> <file> true|false");
        System.exit(1);//  w  w w  .ja  v  a  2s .  c  om
    }

    String to = args[0];
    String from = args[1];
    String host = args[2];
    String filename = args[3];
    boolean debug = Boolean.valueOf(args[4]).booleanValue();
    String msgText1 = "Sending a file.\n";
    String subject = "Sending a file";

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);

    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(msgText1);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        mbp2.attachFile(filename);

        /*
         * Use the following approach instead of the above line if
         * you want to control the MIME type of the attached file.
         * Normally you should never need to do this.
         *
        FileDataSource fds = new FileDataSource(filename) {
        public String getContentType() {
           return "application/octet-stream";
        }
        };
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());
         */

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // set the Date: header
        msg.setSentDate(new Date());

        /*
         * If you want to control the Content-Transfer-Encoding
         * of the attached file, do the following.  Normally you
         * should never need to do this.
         *
        msg.saveChanges();
        mbp2.setHeader("Content-Transfer-Encoding", "base64");
         */

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

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
}

From source file:com.zimbra.cs.util.SmtpInject.java

public static void main(String[] args) {
    CliUtil.toolSetup();// w  w  w. j ava2 s  .c o  m
    CommandLine cl = parseArgs(args);

    if (cl.hasOption("h")) {
        usage(null);
    }

    String file = null;
    if (!cl.hasOption("f")) {
        usage("no file specified");
    } else {
        file = cl.getOptionValue("f");
    }
    try {
        ByteUtil.getContent(new File(file));
    } catch (IOException ioe) {
        usage(ioe.getMessage());
    }

    String host = null;
    if (!cl.hasOption("a")) {
        usage("no smtp server specified");
    } else {
        host = cl.getOptionValue("a");
    }

    String sender = null;
    if (!cl.hasOption("s")) {
        usage("no sender specified");
    } else {
        sender = cl.getOptionValue("s");
    }

    String recipient = null;
    if (!cl.hasOption("r")) {
        usage("no recipient specified");
    } else {
        recipient = cl.getOptionValue("r");
    }

    boolean trace = false;
    if (cl.hasOption("T")) {
        trace = true;
    }

    boolean tls = false;
    if (cl.hasOption("t")) {
        tls = true;
    }

    boolean auth = false;
    String user = null;
    String password = null;
    if (cl.hasOption("A")) {
        auth = true;
        if (!cl.hasOption("u")) {
            usage("auth enabled, no user specified");
        } else {
            user = cl.getOptionValue("u");
        }
        if (!cl.hasOption("p")) {
            usage("auth enabled, no password specified");
        } else {
            password = cl.getOptionValue("p");
        }
    }

    if (cl.hasOption("v")) {
        mLog.info("SMTP server: " + host);
        mLog.info("Sender: " + sender);
        mLog.info("Recipient: " + recipient);
        mLog.info("File: " + file);
        mLog.info("TLS: " + tls);
        mLog.info("Auth: " + auth);
        if (auth) {
            mLog.info("User: " + user);
            char[] dummyPassword = new char[password.length()];
            Arrays.fill(dummyPassword, '*');
            mLog.info("Password: " + new String(dummyPassword));
        }
    }

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host);

    if (auth) {
        props.put("mail.smtp.auth", "true");
    } else {
        props.put("mail.smtp.auth", "false");
    }

    if (tls) {
        props.put("mail.smtp.starttls.enable", "true");
    } else {
        props.put("mail.smtp.starttls.enable", "false");
    }

    // Disable certificate checking so we can test against
    // self-signed certificates
    props.put("mail.smtp.ssl.socketFactory", SocketFactories.dummySSLSocketFactory());

    Session session = Session.getInstance(props, null);
    session.setDebug(trace);

    try {
        // create a message
        MimeMessage msg = new ZMimeMessage(session, new ZSharedFileInputStream(file));
        InternetAddress[] address = { new JavaMailInternetAddress(recipient) };
        msg.setFrom(new JavaMailInternetAddress(sender));

        // attach the file to the message
        Transport transport = session.getTransport("smtp");
        transport.connect(null, user, password);
        transport.sendMessage(msg, address);

    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
        System.exit(1);
    }
}

From source file:Main.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  ww  w. j  a  va  2  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);

    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:org.vosao.utils.EmailUtil.java

/**
 * Send email with html content and attachments.
 * @param htmlBody/* ww  w.j a v a2s .  c o 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:org.vosao.utils.EmailUtil.java

/**
 * Send email with html content and attachments.
 * @param htmlBody/*from  ww  w .ja  v  a2  s  .c  om*/
 * @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()));
            if (mimeType.equals("text/plain")) {
                mimeType = MimeType.DEFAULT;
            }
            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:gt.dakaik.common.Common.java

public static MimeMessage createEmail(String to, String subject, String bodyText) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);

    email.setFrom(new InternetAddress(sendMailFrom));
    email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
    email.setSubject(subject);/*w  w w . j  ava2  s . co  m*/
    email.setText(bodyText);
    return email;
}