Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<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> <p>Here's a full working example using GMail.</p> <pre><code>import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com") private static String PASSWORD = "********"; // GMail password private static String RECIPIENT = "lizard.bill@myschool.edu"; public static void main(String[] args) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // list of recipient email addresses String subject = "Java send mail example"; String body = "Welcome to JavaMail!"; sendFromGMail(from, pass, to, subject, body); } private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i = 0; i &lt; to.length; i++ ) { toAddress[i] = new InternetAddress(to[i]); } for( int i = 0; i &lt; toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } } } </code></pre> <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> <hr> <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>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload