Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Training Introduction to Java Mail Written by Jeff Smith.

Similar presentations


Presentation on theme: "Java Training Introduction to Java Mail Written by Jeff Smith."— Presentation transcript:

1 Java Training Introduction to Java Mail Written by Jeff Smith

2 What is JavaMail? -1 n JavaMail is an API for sending and receiving email using Java. The current version is 1.3.1 and can be downloaded from Sun's website at: http://java.sun.com/products/javamail/ n Possible uses: n Send email from web pages using servlets n Create a GUI email client n Send email from Java stored procedures n Send email from any type of Java application n Spam your friends and enemies! (read email addresses from a database, write a for () loop, and away the emails go!)

3 What is JavaMail? -2 n To send JavaMail, you'll need to add at least two JAR files from Sun to your classpath (placing them in a lib directory may be a good idea) n activation.jar n mail.jar (Note: You can download these files from the Java Zone) n For more complex emailing tasks (like receiving or managing pop3 or imap mail servers), you'll need to download additional files like pop3.jar and imap.jar. n You will also need access to a mail server and possibly a username/password for that mail server

4 How Does Email Work? n In general, each internet domain has an email server. n When you send out an email n Your email client program sends the message to your email server n Your email server contacts the addressee's email server using the SMTP (simple mail transfer protocol) n Your email server verifies that the addressee's user name is valid n Your email server then transfers the email to the addressee's email server n When the addressee logs into his email server (using his email client program), he gets his email

5 Mail Servers (sendmail)-1 n sendmail is the most commonly used mail server in the world, as it generally comes free with Unix and Linux installations n very powerful and flexible. Supports POP3 and IMAP n well documented (lots of books on setting up sendmail) n long track record (first version appeared in early '80s) n tedious to set up (lots of cryptic configuration files) n free n www.sendmail.org

6 Mail Servers (qmail)-2 n qmail is probably the most popular alternative to sendmail in the UNIX world n perhaps more secure than sendmail (at least older versions of sendmail) n Easier to set up and administer than sendmail n pretty good documentation (several books written on qmail in the past few years) n free n http://www.qmail.org/top.html

7 Mail Servers (MS Exchange)-2 n MS Exchange is widely used in the Windows world, especially in corporate environments that use MS Office (and hence MS Outlook) n Expensive n Integrated into MS Active Directory n GUI administration tools are easier to learn for Windows people n MS Outlook is a powerful and slick email program that will work with Exchange, sendmail, or qmail. It does, however, have a history of security vulnerabilities and some organizations refuse to use it because of that.

8 POP3, IMAP, MAPI -1 n Currently, the most popular protocols are n POP3 (Post Office Protocol, version 3) n IMAP (Internet Message Access Protocol) n MAPI (Messaging Application Programming Interface-- Microsoft Windows email interface)

9 POP3 n POP3 is the oldest and most widely used. It was designed to support offline mail processing. n Mail is delivered to a server and a user's computer runs a mail client program to download any new mail n Once messages are delivered, they are generally deleted from the mail server n This minimizes disk space requirements for mail server, but ties the mail to a particular machine. If user goes to another computer, he can't access his mail n POP3 has limited support for reading mail online (and leaving the mail on the mail server) n Simpler protocol than IMAP makes it easier to implement. More POP3 mail clients available

10 IMAP n IMAP n Developed at University of Washington n Primarily used to access mail and leave it on the mail server. This allows users to access their mail from any computer n Requires more disk space to store email messages n Can work in "offline" mode like POP3 n Easy to manage multiple mailboxes n Supports tagging emails with flags like "read", "deleted", "answered", etc.

11 MAPI n MAPI n Set of C functions (API) developed by Microsoft and supported in MS Exchange/Outlook n Also supported by Eudora Mail n For more info, type the following search string in Google: "MAPI site:msdn.microsoft.com"

12 Apache James Mail Server n Apache has a free mail server called James n Supports POP3, SMTP, and NNTP n Download the binary file n.ZIP version (for Windows) n.TAR version (for Linux) n Uncompress it and then run “run.bat” (Windows) or “run.sh” (Linux) to start the mail server Download from here: http://james.apache.org/download.cgi

13 NOAA Mail Server n You can use ESRL/NOAA’s email server email.boulder.noaa.gov mailProperties.setProperty("mail.smtp.host","email.boulder.noaa.gov"); n This will work IF you send emails to @noaa.gov email addresses (like jeff.s.smith@noaa.gov) n When I tried to send an email to jeffssmith1@yahoo.com I got this error message Invalid Address Relaying not allowed: jeffssmith1@yahoo.com

14 Using JavaMail -1 n Once you have a mail server you can use (either James or another mail server), you can send emails through it by using JavaMail n In general, to send a plain text email using JavaMail, you do the following: n Get a mail session instance n Create a MimeMessage object (passing in the mail session instance into the constructor) n Set the MimeMessage object's properties (like the toAddress, fromAddress, message, etc.) n Send the message

15 Getting a Mail Session n Get a mail session for the James mail server. If James is running on your own computer, your mail.smtp.host is localhost. n If your mail server is a remote computer, it might be something like “mailgate.fsl.noaa.gov” n Get a mail session for the James mail server private Session getMailSession() throws Exception { Properties mailProperties = new Properties(); mailProperties.setProperty("mail.transport.protocol", "smtp"); mailProperties.setProperty("mail.smtp.host", " localhost"); return Session.getInstance(mailProperties, null); }

16 Plain Text Email Example n Next, send your email using the mail session MimeMessage msg = new MimeMessage(getMailSession()); msg.setFrom(new InternetAddress("bill.gates@msn.com")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress("larry.ellison@oracle.com")); msg.setSubject("RE: Oracle vs SQL Server"); msg.setText("SQL Server is better than Oracle"); Transport.send(msg);

17 Exceptions and imports n Your code which sends an email will need to catch the following checked exceptions: n Exception n MessagingException n AddressException n You should import the following packages: import javax.mail.*; import javax.mail.internet.*;

18 HTML Email n You can also send HTML email with JavaMail. HTML email can be used to n Use different size fonts n imbed images into your email n Use different colored text, bold, italic, etc.

19 HTML Email n With HTML email, n you set the mime message content type to "text/html" n call the setContent() method to set your html content n It helps to know a little HTML!

20 Mail Security n Virtually all mail servers require a username and password to receive email n Some mail servers require a username and password to send an email (by default, James does not). n This prevents spammers from hijacking the mail server to send unauthorized email n JavaMail supports this username/password authorization and authentication n To implement this, you get a transport object from the mail session and call the connect() method with the mail host, username, and password n See next slide for code example

21 HTML Email Example n Example of sending html message with an imbedded image using username/password authorization MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress("bill@msn.com")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(“tom@msn.com")); msg.setSubject(subject); String html = " MY SPAM <img src='http://www.wrfportal.org/images/NOAA_logo.jpg'> "; msg.setContent(html, "text/html"); Transport transport = mailSession.getTransport("smtp"); transport.connect("localhost","user", "passwd"); msg.saveChanges(); transport.sendMessage(msg, msg.getAllRecipients()); transport.close();

22 Email attachments -1 n To append an email attachment, you need to send a "multipart" message n Create your MimeMessage object as usual, setting the from address, to address, subject, etc... n Create a MimeBodyPart object for your main message and set its text (or content) to be your message n Create a MimeMultiPart object for your attachment and call its setContent() method to attach your file n Create a Multipart object and add both body parts to it. n Call your MimeMessage's setContent() method, passing in your Multipart object n Call Transport.send() to send the message n Whew!!!

23 Email attachment Example-1 MimeMessage msg = new MimeMessage(getMailSession()); msg.setFrom(new InternetAddress("bill.gates@msn.com")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress("larry.ellison@oracle.com")); msg.setSubject("RE: Oracle vs SQL Server"); //Create the main message (body) part MimeBodyPart mainBodyPart = new MimeBodyPart(); mainBodyPart.setText("Here is my message");

24 Email attachment Example-2 //Create attachment body part MimeBodyPart attachBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource("1.jpg"); attachBodyPart.setDataHandler(new DataHandler(source)); attachBodyPart.setFileName("1.jpg"); //Now create the multipart and add the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mainBodyPart); multipart.addBodyPart(attachBodyPart); //add the multipart to the original Mime message msg.setContent(multipart); Transport.send(msg);

25 Exercise -1 n Write a program in package gov.noaa.email that reads a list of email recipients from a disk file and then sends them each an email message. n Use your NOAA webmail account to test this (or you can use our Yahoo email account) n You'll need to: n Create a file and populate it with a list of email addresses (use your own email address or someone else in the class) n Send a single email to all the recipients you read from the db table. n If you are feeling ambitious, you can send an HTML email message. n Use an email client (NOAA webmail?) to verify message delivery n Extra credit: send an email attachment and write an Ant script for your project

26 JavaMail Summary n JavaMail is powerful with good support for things like HTML and attachments n But adding an attachment isn't as simple as it should be. A nice framework (or helper class) would be useful to simplify JavaMail code n JavaMail also supports n receiving email n administering mail servers For an article on receiving email via JavaMail, see: http://www.javaworld.com/javaworld/jw-10-2001/jw-1026- javamail-p2.html


Download ppt "Java Training Introduction to Java Mail Written by Jeff Smith."

Similar presentations


Ads by Google