Tải bản đầy đủ (.pdf) (26 trang)

lập trình mạng nguyễn cao đạt chương 7email sinhvienzone com

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (101.93 KB, 26 trang )

om
.C

Si

nh
Vi
en

Zo

ne

Java Training
Introduction to Java Mail

SinhVienZone.com

/>

What is JavaMail? -1
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:

ne

.C

om


„

nh
Vi
en

Possible uses:
„ Send email from web pages using servlets
„ Create a GUI email client
„ Send email from Java stored procedures
„ Send email from any type of Java application
„ Spam your friends and enemies! (read email addresses
from a database, write a for () loop, and away the emails
go!)

Si

„

Zo

/>
SinhVienZone.com

/>

What is JavaMail? -2

om


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)
„ activation.jar
„ mail.jar

nh
Vi
en

Zo

ne

.C

„

(Note: You can download these files from the Java Zone)
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.
You will also need access to a mail server and possibly a
username/password for that mail server

Si

„

„


SinhVienZone.com

/>

.C

ne

Zo

nh
Vi
en

„

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


Si

„

om

How Does Email Work?

SinhVienZone.com

/>

nh
Vi
en

Zo

ne

.C

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

„ www.sendmail.org

Si

„

om

Mail Servers (sendmail)-1

SinhVienZone.com

/>

nh
Vi
en

Zo

ne

.C

qmail is probably the most popular alternative to sendmail
in the UNIX world
„ perhaps more secure than sendmail (at least older
versions of sendmail)
„ Easier to set up and administer than sendmail
„ pretty good documentation (several books written on

qmail in the past few years)
„ free
„ />
Si

„

om

Mail Servers (qmail)-2

SinhVienZone.com

/>

Mail Servers (MS Exchange)-2
MS Exchange is widely used in the Windows world,
especially in corporate environments that use MS Office
(and hence MS Outlook)
„ Expensive
„ Integrated into MS Active Directory
„ GUI administration tools are easier to learn for Windows
people

„

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.


Si

nh
Vi
en

Zo

ne

.C

om

„

SinhVienZone.com

/>

nh
Vi
en

Zo

Currently, the most popular protocols are
„ POP3 (Post Office Protocol, version 3)
„ IMAP (Internet Message Access Protocol)

„ MAPI (Messaging Application Programming Interface-Microsoft Windows email interface)

Si

„

ne

.C

om

POP3, IMAP, MAPI -1

SinhVienZone.com

/>

POP3

nh
Vi
en

Zo

ne

.C


om

POP3 is the oldest and most widely used. It was designed
to support offline mail processing.
„ Mail is delivered to a server and a user's computer runs
a mail client program to download any new mail
„ Once messages are delivered, they are generally
deleted from the mail server
„ 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
„ POP3 has limited support for reading mail online (and
leaving the mail on the mail server)
„ Simpler protocol than IMAP makes it easier to
implement. More POP3 mail clients available

Si

„

SinhVienZone.com

/>

nh
Vi
en

Zo


ne

.C

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

Si

„

om

IMAP

SinhVienZone.com

/>

nh
Vi
en


Zo

ne

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

Si

„

.C

om

MAPI

SinhVienZone.com

/>

Si

„


nh
Vi
en

Zo

„

.C

„

Apache has a free mail server called James
Supports POP3, SMTP, and NNTP
Download the binary file
„ .ZIP version (for Windows)
„ .TAR version (for Linux)
Uncompress it and then run “run.bat” (Windows) or “run.sh”
(Linux) to start the mail server

ne

„

om

Apache James Mail Server

Download from here:
/>

SinhVienZone.com

/>

om

NOAA Mail Server
You can use ESRL/NOAA’s email server
email.boulder.noaa.gov

.C

„

nh
Vi
en

„

This will work IF you send emails to @noaa.gov email
addresses (like )
When I tried to send an email to I got
this error message

Si

„

Zo


ne

mailProperties.setProperty("mail.smtp.host","email.boulder.noaa.gov");

Invalid Address
Relaying not allowed:

SinhVienZone.com

/>

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

Zo

nh
Vi
en


Si

„

ne

.C

„

om

Using JavaMail -1

SinhVienZone.com

/>

Getting a Mail Session

om

.C

nh
Vi
en

„


ne

„

Get a mail session for the James mail server. If James is
running on your own computer, your mail.smtp.host is
localhost.
If your mail server is a remote computer, it might be
something like “mailgate.fsl.noaa.gov”
Get a mail session for the James mail server

Zo

„

Si

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);
}
SinhVienZone.com

/>


Next, send your email using the mail session

.C

„

om

Plain Text Email Example

Si

nh
Vi
en

Zo

ne

MimeMessage msg = new MimeMessage(getMailSession());
msg.setFrom(new InternetAddress(""));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(""));
msg.setSubject("RE: Oracle vs SQL Server");
msg.setText("SQL Server is better than Oracle");
Transport.send(msg);

SinhVienZone.com


/>

om

Exceptions and imports
Your code which sends an email will need to catch the
following checked exceptions:
„ Exception
„ MessagingException
„ AddressException

„

You should import the following packages:

Si

nh
Vi
en

Zo

ne

.C

„


import javax.mail.*;
import javax.mail.internet.*;

SinhVienZone.com

/>

Zo

ne

You can also send HTML email with JavaMail. HTML email
can be used to
Use different size fonts

„

imbed images into your email

„

Use different colored text, bold, italic, etc.

nh
Vi
en

„

Si


„

.C

om

HTML Email

SinhVienZone.com

/>

nh
Vi
en

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

Si

„

Zo

ne


.C

om

HTML Email

SinhVienZone.com

/>

.C

Si

„

nh
Vi
en

Zo

„

Virtually all mail servers require a username and password
to receive email
Some mail servers require a username and password to
send an email (by default, James does not).
„ This prevents spammers from hijacking the mail server
to send unauthorized email

JavaMail supports this username/password authorization
and authentication
„ To implement this, you get a transport object from the
mail session and call the connect() method with the mail
host, username, and password
„ See next slide for code example

ne

„

om

Mail Security

SinhVienZone.com

/>

HTML Email Example
Example of sending html message with an imbedded image
using username/password authorization

om

„

Si

nh

Vi
en

Zo

ne

.C

MimeMessage msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(""));
msg.addRecipient(Message.RecipientType.TO, new
InternetAddress(“"));
msg.setSubject(subject);
String html = "<html><body><b>MY SPAM</b>
src=' /></body></html>";
msg.setContent(html, "text/html");
Transport transport = mailSession.getTransport("smtp");
transport.connect("localhost","user", "passwd");
msg.saveChanges();
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
SinhVienZone.com

/>

Email attachments -1

om


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

Si

nh
Vi
en

Zo

ne

.C

„

„


SinhVienZone.com

/>

om

Email attachment Example-1

nh
Vi
en

Zo

ne

.C

MimeMessage msg = new MimeMessage(getMailSession());
msg.setFrom(new InternetAddress(""));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(""));
msg.setSubject("RE: Oracle vs SQL Server");

Si

//Create the main message (body) part
MimeBodyPart mainBodyPart = new MimeBodyPart();
mainBodyPart.setText("Here is my message");


SinhVienZone.com

/>

Email attachment Example-2

Zo

ne

.C

om

//Create attachment body part
MimeBodyPart attachBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource("1.jpg");
attachBodyPart.setDataHandler(new DataHandler(source));
attachBodyPart.setFileName("1.jpg");

Si

nh
Vi
en

//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);

SinhVienZone.com

/>

„

.C

Si

nh
Vi
en

„

ne

„

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.
Use your NOAA webmail account to test this (or you can use our Yahoo
email account)
You'll need to:
„

Create a file and populate it with a list of email addresses (use your
own email address or someone else in the class)
„
Send a single email to all the recipients you read from the db table.
„
If you are feeling ambitious, you can send an HTML email message.
„
Use an email client (NOAA webmail?) to verify message delivery
Extra credit: send an email attachment and write an Ant script for your
project

Zo

„

om

Exercise -1

SinhVienZone.com

/>

×