<p>Is it possible to send an email from my Java application using a GMail account?  I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.</p>

[{'answer_id': 46676, 'author': 'Ryan Farley', 'author_id': 1627, 'author_profile': 'https://Stackoverflow.com/users/1627', 'pm_score': 0, 'selected': False, 'text': "<p>An easy route would be to have the gmail account configured/enabled for POP3 access. This would allow you to send out via normal SMTP through the gmail servers.   </p>\n\n<p>Then you'd just send through smtp.gmail.com (on port 587)</p>\n"}, {'answer_id': 46681, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 7, 'selected': False, 'text': '<p>Something like this (sounds like you just need to change your SMTP server):</p>\n\n<pre><code>String host = "smtp.gmail.com";\nString from = "user name";\nProperties props = System.getProperties();\nprops.put("mail.smtp.host", host);\nprops.put("mail.smtp.user", from);\nprops.put("mail.smtp.password", "asdfgh");\nprops.put("mail.smtp.port", "587"); // 587 is the port number of yahoo mail\nprops.put("mail.smtp.auth", "true");\n\nSession session = Session.getDefaultInstance(props, null);\nMimeMessage message = new MimeMessage(session);\nmessage.setFrom(new InternetAddress(from));\n\nInternetAddress[] to_address = new InternetAddress[to.length];\nint i = 0;\n// To get the array of addresses\nwhile (to[i] != null) {\n    to_address[i] = new InternetAddress(to[i]);\n    i++;\n}\nSystem.out.println(Message.RecipientType.TO);\ni = 0;\nwhile (to_address[i] != null) {\n\n    message.addRecipient(Message.RecipientType.TO, to_address[i]);\n    i++;\n}\nmessage.setSubject("sending in a group");\nmessage.setText("Welcome to JavaMail");\n// alternately, to send HTML mail:\n// message.setContent("&lt;p&gt;Welcome to JavaMail&lt;/p&gt;", "text/html");\nTransport transport = session.getTransport("smtp");\ntransport.connect("smtp.mail.yahoo.co.in", "user name", "asdfgh");\ntransport.sendMessage(message, message.getAllRecipients());\ntransport.close();\n</code></pre>\n'}, {'answer_id': 47452, 'author': 'Bill the Lizard', 'author_id': 1288, 'author_profile': 'https://Stackoverflow.com/users/1288', 'pm_score': 9, 'selected': True, 'text': '<p>First download the <a href="https://java.net/projects/javamail/pages/Home" rel="noreferrer">JavaMail API</a> and make sure the relevant jar files are in your classpath.</p>\n\n<p>Here\'s a full working example using GMail.</p>\n\n<pre><code>import java.util.*;\nimport javax.mail.*;\nimport javax.mail.internet.*;\n\npublic class Main {\n\n    private static String USER_NAME = "*****";  // GMail user name (just the part before "@gmail.com")\n    private static String PASSWORD = "********"; // GMail password\n    private static String RECIPIENT = "lizard.bill@myschool.edu";\n\n    public static void main(String[] args) {\n        String from = USER_NAME;\n        String pass = PASSWORD;\n        String[] to = { RECIPIENT }; // list of recipient email addresses\n        String subject = "Java send mail example";\n        String body = "Welcome to JavaMail!";\n\n        sendFromGMail(from, pass, to, subject, body);\n    }\n\n    private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {\n        Properties props = System.getProperties();\n        String host = "smtp.gmail.com";\n        props.put("mail.smtp.starttls.enable", "true");\n        props.put("mail.smtp.host", host);\n        props.put("mail.smtp.user", from);\n        props.put("mail.smtp.password", pass);\n        props.put("mail.smtp.port", "587");\n        props.put("mail.smtp.auth", "true");\n\n        Session session = Session.getDefaultInstance(props);\n        MimeMessage message = new MimeMessage(session);\n\n        try {\n            message.setFrom(new InternetAddress(from));\n            InternetAddress[] toAddress = new InternetAddress[to.length];\n\n            // To get the array of addresses\n            for( int i = 0; i &lt; to.length; i++ ) {\n                toAddress[i] = new InternetAddress(to[i]);\n            }\n\n            for( int i = 0; i &lt; toAddress.length; i++) {\n                message.addRecipient(Message.RecipientType.TO, toAddress[i]);\n            }\n\n            message.setSubject(subject);\n            message.setText(body);\n            Transport transport = session.getTransport("smtp");\n            transport.connect(host, from, pass);\n            transport.sendMessage(message, message.getAllRecipients());\n            transport.close();\n        }\n        catch (AddressException ae) {\n            ae.printStackTrace();\n        }\n        catch (MessagingException me) {\n            me.printStackTrace();\n        }\n    }\n}\n</code></pre>\n\n<p>Naturally, you\'ll want to do more in the <code>catch</code> blocks than print the stack trace as I did in the example code above.  (Remove the <code>catch</code> blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)</p>\n\n<hr>\n\n<p>Thanks to <a href="https://stackoverflow.com/users/4223/jodonnell">@jodonnel</a> and everyone else who answered.  I\'m giving him a bounty because his answer led me about 95% of the way to a complete answer.</p>\n'}, {'answer_id': 886689, 'author': 'user109771', 'author_id': 109771, 'author_profile': 'https://Stackoverflow.com/users/109771', 'pm_score': 4, 'selected': False, 'text': '<p>Even though this question is closed, I\'d like to post a counter solution, but now using <a href="http://www.simplejavamail.org" rel="nofollow noreferrer">Simple Java Mail</a> (Open Source JavaMail smtp wrapper):</p>\n\n<pre><code>final Email email = new Email();\n\nString host = "smtp.gmail.com";\nInteger port = 587;\nString from = "username";\nString pass = "password";\nString[] to = {"to@gmail.com"};\n\nemail.setFromAddress("", from);\nemail.setSubject("sending in a group");\nfor( int i=0; i &lt; to.length; i++ ) {\n    email.addRecipient("", to[i], RecipientType.TO);\n}\nemail.setText("Welcome to JavaMail");\n\nnew Mailer(host, port, from, pass).sendMail(email);\n// you could also still use your mail session instead\nnew Mailer(session).sendMail(email);\n</code></pre>\n'}, {'answer_id': 935714, 'author': 'Ifnu', 'author_id': 115520, 'author_profile': 'https://Stackoverflow.com/users/115520', 'pm_score': 1, 'selected': False, 'text': '<p>This is what I do when i want to send email with attachment, work fine. :)</p>\n\n<pre><code> public class NewClass {\n\n    public static void main(String[] args) {\n        try {\n            Properties props = System.getProperties();\n            props.put("mail.smtp.starttls.enable", "true");\n            props.put("mail.smtp.host", "smtp.gmail.com");\n            props.put("mail.smtp.auth", "true");\n            props.put("mail.smtp.port", "465"); // smtp port\n            Authenticator auth = new Authenticator() {\n\n                @Override\n                protected PasswordAuthentication getPasswordAuthentication() {\n                    return new PasswordAuthentication("username-gmail", "password-gmail");\n                }\n            };\n            Session session = Session.getDefaultInstance(props, auth);\n            MimeMessage msg = new MimeMessage(session);\n            msg.setFrom(new InternetAddress("username-gmail@gmail.com"));\n            msg.setSubject("Try attachment gmail");\n            msg.setRecipient(RecipientType.TO, new InternetAddress("username-gmail@gmail.com"));\n            //add atleast simple body\n            MimeBodyPart body = new MimeBodyPart();\n            body.setText("Try attachment");\n            //do attachment\n            MimeBodyPart attachMent = new MimeBodyPart();\n            FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));\n            attachMent.setDataHandler(new DataHandler(dataSource));\n            attachMent.setFileName("file-sent.txt");\n            attachMent.setDisposition(MimeBodyPart.ATTACHMENT);\n            Multipart multipart = new MimeMultipart();\n            multipart.addBodyPart(body);\n            multipart.addBodyPart(attachMent);\n            msg.setContent(multipart);\n            Transport.send(msg);\n        } catch (AddressException ex) {\n            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);\n        } catch (MessagingException ex) {\n            Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);\n        }\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 1013676, 'author': 'Jason Thrasher', 'author_id': 124754, 'author_profile': 'https://Stackoverflow.com/users/124754', 'pm_score': 5, 'selected': False, 'text': '<p>Other people have good answers above, but I wanted to add a note on my experience here.  I\'ve found that when using Gmail as an outbound SMTP server for my webapp, Gmail only lets me send ~10 or so messages before responding with an anti-spam response that I have to manually step through to re-enable SMTP access.  The emails I was sending were not spam, but were website "welcome" emails when users registered with my system.  So, YMMV, and I wouldn\'t rely on Gmail for a production webapp.  If you\'re sending email on a user\'s behalf, like an installed desktop app (where the user enters their own Gmail credentials), you may be okay.</p>\n\n<p>Also, if you\'re using Spring, here\'s a working config to use Gmail for outbound SMTP:</p>\n\n<pre><code>&lt;bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt;\n    &lt;property name="defaultEncoding" value="UTF-8"/&gt;\n    &lt;property name="host" value="smtp.gmail.com"/&gt;\n    &lt;property name="port" value="465"/&gt;\n    &lt;property name="username" value="${mail.username}"/&gt;\n    &lt;property name="password" value="${mail.password}"/&gt;\n    &lt;property name="javaMailProperties"&gt;\n        &lt;value&gt;\n            mail.debug=true\n            mail.smtp.auth=true\n            mail.smtp.socketFactory.class=java.net.SocketFactory\n            mail.smtp.socketFactory.fallback=false\n        &lt;/value&gt;\n    &lt;/property&gt;\n&lt;/bean&gt;\n</code></pre>\n'}, {'answer_id': 3970608, 'author': 'vishnu', 'author_id': 480749, 'author_profile': 'https://Stackoverflow.com/users/480749', 'pm_score': 2, 'selected': False, 'text': '<pre><code>//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar\nimport javax.mail.*;\nimport javax.mail.internet.*;\nimport java.util.*;\n\npublic class Mail\n{\n    String  d_email = "iamdvr@gmail.com",\n            d_password = "****",\n            d_host = "smtp.gmail.com",\n            d_port  = "465",\n            m_to = "iamdvr@yahoo.com",\n            m_subject = "Testing",\n            m_text = "Hey, this is the testing email using smtp.gmail.com.";\n    public static void main(String[] args)\n    {\n        String[] to={"XXX@yahoo.com"};\n        String[] cc={"XXX@yahoo.com"};\n        String[] bcc={"XXX@yahoo.com"};\n        //This is for google\n        Mail.sendMail("venkatesh@dfdf.com", "password", "smtp.gmail.com", \n                      "465", "true", "true", \n                      true, "javax.net.ssl.SSLSocketFactory", "false", \n                      to, cc, bcc, \n                      "hi baba don\'t send virus mails..", \n                      "This is my style...of reply..If u send virus mails..");\n    }\n\n    public synchronized static boolean sendMail(\n        String userName, String passWord, String host, \n        String port, String starttls, String auth, \n        boolean debug, String socketFactoryClass, String fallback, \n        String[] to, String[] cc, String[] bcc, \n        String subject, String text) \n    {\n        Properties props = new Properties();\n        //Properties props=System.getProperties();\n        props.put("mail.smtp.user", userName);\n        props.put("mail.smtp.host", host);\n        if(!"".equals(port))\n            props.put("mail.smtp.port", port);\n        if(!"".equals(starttls))\n            props.put("mail.smtp.starttls.enable",starttls);\n        props.put("mail.smtp.auth", auth);\n        if(debug) {\n            props.put("mail.smtp.debug", "true");\n        } else {\n            props.put("mail.smtp.debug", "false");         \n        }\n        if(!"".equals(port))\n            props.put("mail.smtp.socketFactory.port", port);\n        if(!"".equals(socketFactoryClass))\n            props.put("mail.smtp.socketFactory.class",socketFactoryClass);\n        if(!"".equals(fallback))\n            props.put("mail.smtp.socketFactory.fallback", fallback);\n\n        try\n        {\n            Session session = Session.getDefaultInstance(props, null);\n            session.setDebug(debug);\n            MimeMessage msg = new MimeMessage(session);\n            msg.setText(text);\n            msg.setSubject(subject);\n            msg.setFrom(new InternetAddress("p_sambasivarao@sutyam.com"));\n            for(int i=0;i&lt;to.length;i++) {\n                msg.addRecipient(Message.RecipientType.TO, \n                                 new InternetAddress(to[i]));\n            }\n            for(int i=0;i&lt;cc.length;i++) {\n                msg.addRecipient(Message.RecipientType.CC, \n                                 new InternetAddress(cc[i]));\n            }\n            for(int i=0;i&lt;bcc.length;i++) {\n                msg.addRecipient(Message.RecipientType.BCC, \n                                 new InternetAddress(bcc[i]));\n            }\n            msg.saveChanges();\n            Transport transport = session.getTransport("smtp");\n            transport.connect(host, userName, passWord);\n            transport.sendMessage(msg, msg.getAllRecipients());\n            transport.close();\n            return true;\n        }\n        catch (Exception mex)\n        {\n            mex.printStackTrace();\n            return false;\n        }\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 14191227, 'author': 'Ripon Al Wasim', 'author_id': 617450, 'author_profile': 'https://Stackoverflow.com/users/617450', 'pm_score': 3, 'selected': False, 'text': '<p>My complete code as below is working well:</p>\n\n<pre><code>package ripon.java.mail;\nimport java.util.*;\nimport javax.mail.*;\nimport javax.mail.internet.*;\n\npublic class SendEmail\n{\npublic static void main(String [] args)\n{    \n    // Sender\'s email ID needs to be mentioned\n     String from = "test@gmail.com";\n     String pass ="test123";\n    // Recipient\'s email ID needs to be mentioned.\n   String to = "ripon420@yahoo.com";\n\n   String host = "smtp.gmail.com";\n\n   // Get system properties\n   Properties properties = System.getProperties();\n   // Setup mail server\n   properties.put("mail.smtp.starttls.enable", "true");\n   properties.put("mail.smtp.host", host);\n   properties.put("mail.smtp.user", from);\n   properties.put("mail.smtp.password", pass);\n   properties.put("mail.smtp.port", "587");\n   properties.put("mail.smtp.auth", "true");\n\n   // Get the default Session object.\n   Session session = Session.getDefaultInstance(properties);\n\n   try{\n      // Create a default MimeMessage object.\n      MimeMessage message = new MimeMessage(session);\n\n      // Set From: header field of the header.\n      message.setFrom(new InternetAddress(from));\n\n      // Set To: header field of the header.\n      message.addRecipient(Message.RecipientType.TO,\n                               new InternetAddress(to));\n\n      // Set Subject: header field\n      message.setSubject("This is the Subject Line!");\n\n      // Now set the actual message\n      message.setText("This is actual message");\n\n      // Send message\n      Transport transport = session.getTransport("smtp");\n      transport.connect(host, from, pass);\n      transport.sendMessage(message, message.getAllRecipients());\n      transport.close();\n      System.out.println("Sent message successfully....");\n   }catch (MessagingException mex) {\n      mex.printStackTrace();\n   }\n}\n}\n</code></pre>\n'}, {'answer_id': 20550855, 'author': 'Bryan', 'author_id': 908570, 'author_profile': 'https://Stackoverflow.com/users/908570', 'pm_score': 2, 'selected': False, 'text': '<p>The posted code solutions may cause problems when you need to set up multiple SMTP sessions anywhere within the same JVM.</p>\n\n<p>The JavaMail FAQ recommends using</p>\n\n<pre><code>Session.getInstance(properties);\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>Session.getDefaultInstance(properties);\n</code></pre>\n\n<p>because the getDefault will only use the properties given the first time it is invoked. All later uses of the default instance will ignore property changes.</p>\n\n<p>See <a href="http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance" rel="nofollow">http://www.oracle.com/technetwork/java/faq-135477.html#getdefaultinstance</a></p>\n'}, {'answer_id': 21800051, 'author': 'Pyare', 'author_id': 1911977, 'author_profile': 'https://Stackoverflow.com/users/1911977', 'pm_score': 0, 'selected': False, 'text': '<p>Hi try this code....</p>\n\n<pre><code>package my.test.service;\n\nimport java.util.Properties;\n\nimport javax.mail.Authenticator;\nimport javax.mail.MessagingException;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Message;\nimport javax.mail.Transport;\nimport javax.mail.internet.AddressException;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\npublic class Sample {\n    public static void main(String args[]) {\n        final String SMTP_HOST = "smtp.gmail.com";\n        final String SMTP_PORT = "587";\n        final String GMAIL_USERNAME = "xxxxxxxxxx@gmail.com";\n        final String GMAIL_PASSWORD = "xxxxxxxxxx";\n\n        System.out.println("Process Started");\n\n        Properties prop = System.getProperties();\n        prop.setProperty("mail.smtp.starttls.enable", "true");\n        prop.setProperty("mail.smtp.host", SMTP_HOST);\n        prop.setProperty("mail.smtp.user", GMAIL_USERNAME);\n        prop.setProperty("mail.smtp.password", GMAIL_PASSWORD);\n        prop.setProperty("mail.smtp.port", SMTP_PORT);\n        prop.setProperty("mail.smtp.auth", "true");\n        System.out.println("Props : " + prop);\n\n        Session session = Session.getInstance(prop, new Authenticator() {\n            protected PasswordAuthentication getPasswordAuthentication() {\n                return new PasswordAuthentication(GMAIL_USERNAME,\n                        GMAIL_PASSWORD);\n            }\n        });\n\n        System.out.println("Got Session : " + session);\n\n        MimeMessage message = new MimeMessage(session);\n        try {\n            System.out.println("before sending");\n            message.setFrom(new InternetAddress(GMAIL_USERNAME));\n            message.addRecipients(Message.RecipientType.TO,\n                    InternetAddress.parse(GMAIL_USERNAME));\n            message.setSubject("My First Email Attempt from Java");\n            message.setText("Hi, This mail came from Java Application.");\n            message.setRecipients(Message.RecipientType.TO,\n                    InternetAddress.parse(GMAIL_USERNAME));\n            Transport transport = session.getTransport("smtp");\n            System.out.println("Got Transport" + transport);\n            transport.connect(SMTP_HOST, GMAIL_USERNAME, GMAIL_PASSWORD);\n            transport.sendMessage(message, message.getAllRecipients());\n            System.out.println("message Object : " + message);\n            System.out.println("Email Sent Successfully");\n        } catch (AddressException e) {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        } catch (MessagingException e) {\n            // TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 27402060, 'author': 'AlikElzin-kilaka', 'author_id': 435605, 'author_profile': 'https://Stackoverflow.com/users/435605', 'pm_score': 2, 'selected': False, 'text': '<p>The minimum required:</p>\n\n<pre><code>import java.util.Properties;\n\nimport javax.mail.Message;\nimport javax.mail.MessagingException;\nimport javax.mail.PasswordAuthentication;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.AddressException;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\npublic class MessageSender {\n\n    public static void sendHardCoded() throws AddressException, MessagingException {\n        String to = "a@a.info";\n        final String from = "b@gmail.com";\n\n        Properties properties = new Properties();\n        properties.put("mail.smtp.starttls.enable", "true");\n        properties.put("mail.smtp.auth", "true");\n        properties.put("mail.smtp.host", "smtp.gmail.com");\n        properties.put("mail.smtp.port", "587");\n\n        Session session = Session.getInstance(properties,\n                new javax.mail.Authenticator() {\n                    protected PasswordAuthentication getPasswordAuthentication() {\n                        return new PasswordAuthentication(from, "BeNice");\n                    }\n                });\n\n        MimeMessage message = new MimeMessage(session);\n        message.setFrom(new InternetAddress(from));\n        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));\n        message.setSubject("Hello");\n        message.setText("What\'s up?");\n\n        Transport.send(message);\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 31224370, 'author': 'BullyWiiPlaza', 'author_id': 3764804, 'author_profile': 'https://Stackoverflow.com/users/3764804', 'pm_score': 0, 'selected': False, 'text': '<p>Here\'s an easy-to-use class for sending emails with <a href="https://mail.google.com/" rel="nofollow"><code>Gmail</code></a>. You need to have the <a href="https://java.net/projects/javamail/pages/Home" rel="nofollow"><code>JavaMail</code></a> library <a href="http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)" rel="nofollow">added to your build path</a> or just use <a href="http://mvnrepository.com/artifact/javax.mail" rel="nofollow"><code>Maven</code></a>.</p>\n\n<pre><code>import java.util.Properties;\n\nimport javax.activation.DataHandler;\nimport javax.activation.DataSource;\nimport javax.activation.FileDataSource;\nimport javax.mail.BodyPart;\nimport javax.mail.Message;\nimport javax.mail.MessagingException;\nimport javax.mail.Multipart;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.internet.AddressException;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeBodyPart;\nimport javax.mail.internet.MimeMessage;\nimport javax.mail.internet.MimeMultipart;\n\npublic class GmailSender\n{\n    private static String protocol = "smtp";\n\n    private String username;\n    private String password;\n\n    private Session session;\n    private Message message;\n    private Multipart multipart;\n\n    public GmailSender()\n    {\n        this.multipart = new MimeMultipart();\n    }\n\n    public void setSender(String username, String password)\n    {\n        this.username = username;\n        this.password = password;\n\n        this.session = getSession();\n        this.message = new MimeMessage(session);\n    }\n\n    public void addRecipient(String recipient) throws AddressException, MessagingException\n    {\n        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));\n    }\n\n    public void setSubject(String subject) throws MessagingException\n    {\n        message.setSubject(subject);\n    }\n\n    public void setBody(String body) throws MessagingException\n    {\n        BodyPart messageBodyPart = new MimeBodyPart();\n        messageBodyPart.setText(body);\n        multipart.addBodyPart(messageBodyPart);\n\n        message.setContent(multipart);\n    }\n\n    public void send() throws MessagingException\n    {\n        Transport transport = session.getTransport(protocol);\n        transport.connect(username, password);\n        transport.sendMessage(message, message.getAllRecipients());\n\n        transport.close();\n    }\n\n    public void addAttachment(String filePath) throws MessagingException\n    {\n        BodyPart messageBodyPart = getFileBodyPart(filePath);\n        multipart.addBodyPart(messageBodyPart);\n\n        message.setContent(multipart);\n    }\n\n    private BodyPart getFileBodyPart(String filePath) throws MessagingException\n    {\n        BodyPart messageBodyPart = new MimeBodyPart();\n        DataSource dataSource = new FileDataSource(filePath);\n        messageBodyPart.setDataHandler(new DataHandler(dataSource));\n        messageBodyPart.setFileName(filePath);\n\n        return messageBodyPart;\n    }\n\n    private Session getSession()\n    {\n        Properties properties = getMailServerProperties();\n        Session session = Session.getDefaultInstance(properties);\n\n        return session;\n    }\n\n    private Properties getMailServerProperties()\n    {\n        Properties properties = System.getProperties();\n        properties.put("mail.smtp.starttls.enable", "true");\n        properties.put("mail.smtp.host", protocol + ".gmail.com");\n        properties.put("mail.smtp.user", username);\n        properties.put("mail.smtp.password", password);\n        properties.put("mail.smtp.port", "587");\n        properties.put("mail.smtp.auth", "true");\n\n        return properties;\n    }\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>GmailSender sender = new GmailSender();\nsender.setSender("myEmailNameWithout@gmail.com", "mypassword");\nsender.addRecipient("recipient@somehost.com");\nsender.setSubject("The subject");\nsender.setBody("The body");\nsender.addAttachment("TestFile.txt");\nsender.send();\n</code></pre>\n'}, {'answer_id': 41347492, 'author': 'Inzimam Tariq IT', 'author_id': 5055401, 'author_profile': 'https://Stackoverflow.com/users/5055401', 'pm_score': 0, 'selected': False, 'text': '<p>If you want to use outlook with <code>Javamail API</code> then use </p>\n\n<pre><code>smtp-mail.outlook.com\n</code></pre>\n\n<p>as a <strong>host</strong> for more and complete working code <a href="https://stackoverflow.com/questions/39218352/how-to-send-an-email-from-outlook-via-java/41347253#41347253">Check out this answer</a>.</p>\n'}, {'answer_id': 62555019, 'author': 'Reto Höhener', 'author_id': 1124509, 'author_profile': 'https://Stackoverflow.com/users/1124509', 'pm_score': 2, 'selected': False, 'text': '<p>Value added:</p>\n<ul>\n<li><strong>encoding pitfalls</strong> in subject, message and display name</li>\n<li><strong>only one magic property</strong> is needed for modern java mail library versions</li>\n<li><code>Session.getInstance()</code> recommended over <code>Session.getDefaultInstance()</code></li>\n<li><strong>attachment</strong> in the same example</li>\n<li><strong>still works</strong> after <a href="https://gsuiteupdates.googleblog.com/2019/12/less-secure-apps-oauth-google-username-password-incorrect.html" rel="nofollow noreferrer">Google turns off less secure apps</a>: Enable 2-factor authentication in your organization -&gt; turn on 2FA -&gt; generate app password.</li>\n</ul>\n<pre><code>    import java.io.File;\n    import java.nio.charset.StandardCharsets;\n    import java.util.Properties;\n    import java.util.logging.Level;\n    import java.util.logging.Logger;\n    import javax.activation.DataHandler;\n    import javax.mail.Message;\n    import javax.mail.Session;\n    import javax.mail.Transport;\n    import javax.mail.internet.InternetAddress;\n    import javax.mail.internet.MimeBodyPart;\n    import javax.mail.internet.MimeMessage;\n    import javax.mail.internet.MimeMultipart;\n    import javax.mail.util.ByteArrayDataSource;\n    \n    public class Gmailer {\n      private static final Logger LOGGER = Logger.getLogger(Gmailer.class.getName());\n    \n      public static void main(String[] args) {\n        send();\n      }\n    \n      public static void send() {\n        Transport transport = null;\n        try {\n          String accountEmail = &quot;account@source.com&quot;;\n          String accountAppPassword = &quot;&quot;;\n          String displayName = &quot;Display-Name 東&quot;;\n          String replyTo = &quot;reply-to@source.com&quot;;\n    \n          String to = &quot;to@target.com&quot;;\n          String cc = &quot;cc@target.com&quot;;\n          String bcc = &quot;bcc@target.com&quot;;\n    \n          String subject = &quot;Subject 東&quot;;\n          String message = &quot;&lt;span style=\'color: red;\'&gt;東&lt;/span&gt;&quot;;\n          String type = &quot;html&quot;; // or &quot;plain&quot;\n          String mimeTypeWithEncoding = &quot;text/&quot; + type + &quot;; charset=&quot; + StandardCharsets.UTF_8.name();\n    \n          File attachmentFile = new File(&quot;Attachment.pdf&quot;);\n          // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types\n          String attachmentMimeType = &quot;application/pdf&quot;;\n          byte[] bytes = ...; // read file to byte array\n    \n          Properties properties = System.getProperties();\n          properties.put(&quot;mail.debug&quot;, &quot;true&quot;);\n          // i found that this is the only property necessary for a modern java mail version\n          properties.put(&quot;mail.smtp.starttls.enable&quot;, &quot;true&quot;);\n          // https://javaee.github.io/javamail/FAQ#getdefaultinstance\n          Session session = Session.getInstance(properties);\n    \n          MimeMessage mimeMessage = new MimeMessage(session);\n    \n          // probably best to use the account email address, to avoid landing in spam or blacklists\n          // not even sure if the server would accept a differing from address\n          InternetAddress from = new InternetAddress(accountEmail);\n          from.setPersonal(displayName, StandardCharsets.UTF_8.name());\n          mimeMessage.setFrom(from);\n    \n          mimeMessage.setReplyTo(InternetAddress.parse(replyTo));\n    \n          mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));\n          mimeMessage.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));\n          mimeMessage.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));\n    \n          mimeMessage.setSubject(subject, StandardCharsets.UTF_8.name());\n    \n          MimeMultipart multipart = new MimeMultipart();\n    \n          MimeBodyPart messagePart = new MimeBodyPart();\n          messagePart.setContent(mimeMessage, mimeTypeWithEncoding);\n          multipart.addBodyPart(messagePart);\n    \n          MimeBodyPart attachmentPart = new MimeBodyPart();\n          attachmentPart.setDataHandler(new DataHandler(new ByteArrayDataSource(bytes, attachmentMimeType)));\n          attachmentPart.setFileName(attachmentFile.getName());\n          multipart.addBodyPart(attachmentPart);\n    \n          mimeMessage.setContent(multipart);\n    \n          transport = session.getTransport();\n          transport.connect(&quot;smtp.gmail.com&quot;, 587, accountEmail, accountAppPassword);\n          transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());\n        }\n        catch(Exception e) {\n          // I prefer to bubble up exceptions, so the caller has the info that someting went wrong, and gets a chance to handle it.\n          // I also prefer not to force the exception in the signature.\n          throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e);\n        }\n        finally {\n          if(transport != null) {\n            try {\n              transport.close();\n            }\n            catch(Exception e) {\n              LOGGER.log(Level.WARNING, &quot;failed to close java mail transport: &quot; + e);\n            }\n          }\n        }\n      }\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/46663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1288/']