email me at borlaj@portlandschools.org

Loading
notes previous (11/<11) submit the dump links  
 

Sending Mail

 

To send an email we need to use code created by others. When people want to share code, they often compile it and compress it as a library file (known as JAR file). We dont include it as we include as we would just a class (because its compiled).

 

  • The JAR file that you need to use is here. (SAVE IT TO YOUR FOLDER THAT YOU ARE WORKING WITH)
  • In BLUEJ - click preferences - Add library and find that jar file.

Have these imports:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties; 

 

Now add the code below as a method and call it. Replace the username pwd with yours if you want.

    public void sendMail(String to, String subject, String body){
        try{
            final String SMTP_HOST_NAME = "smtp.gmail.com";
            final int SMTP_HOST_PORT = 465;
            final String SMTP_AUTH_USER = "deeringCS@gmail.com";
            final String SMTP_AUTH_PWD  = "mrborland";

            Properties props = new Properties();
            props.put("mail.transport.protocol", "smtps");
            props.put("mail.smtps.host", SMTP_HOST_NAME);
            props.put("mail.smtps.auth", "true");

            Session mailSession = Session.getDefaultInstance(props);
            mailSession.setDebug(true);
            Transport transport = mailSession.getTransport();

            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject);
            message.setContent(body, "text/plain");

            message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(to));

            transport.connect
            (SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

            transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
            transport.close();
        }
        catch (Exception e){}
    }