lect-5 java emailing
TRANSCRIPT
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 1/33
Contents Advanced Socket Programming
Socket Timeouts
Interruptible Sockets Half-close
Internet Address
Java Mail Messaging System
1
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 2/33
Socket Timeouts Problem:If the host is unreachable,
then your application waits for a long
time or read methods will block untildata are available so.
Java offers Socket.setSoTimeout tocontrol how long you are willing to
wait for a read to complete.
Decide what time out value isreasonable for your application.
2
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 3/33
Then call the setSoTimeout method to set atime out value(in milliseconds)
Socket s=new Socket(«.);
S.setSoTimeout(10000);//time out after 10seconds.
If the time out value has been set for asocket,then all subsequent read and write
operations throw a SocketTimeoutExceptionwhen the time out has been reached before theoperation has completed its work.
3
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 4/33
Case-2: The constructor Socket(String host,int port)can block indefinitely until an initial connection to thehost is established.
Solution: First construct an unconnected socket andthen connecting it with a timeout.
Socket s=new Socket();
s.connect(new InetSocketAddress(host,port),timeout);
4
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 5/33
Interruptible sockets Gives user an option to simply cancel
a socket connection that does not
appear to produce results. For ex in a client server application if
the server pretends to be busy anddoes send any reply to the
client..client can click cancel button toterminate the connection.
5
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 6/33
To interrupt a socket operation ,SocketChannelis used,a feature of the java.nio package.
SocketChannel
channel=SocketChannel.open(newInetSocketAddress(host,port));
Whenever a thread is interrupted during anopen ,read or write operation ,the operation
does not block but is terminated with anexception
6
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 7/33
Half-close When a client program sends a request to the
server, server needs to be able to determinewhen the end of request occurs.
This can be accomplished by closing the outputstream of a socket, thereby indicating to theserver the end of the request data, but keepingthe input stream open to read the response
coming from server. So if you want to shut down only half of the
connection, either input or output -the
shutdownInput() and shutdownOutput method
7
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 8/33
Let you close only half of theconnection.
This down not close the socket
8
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 9/33
Internet Address InetAddress class ->used to convert between host
names and internet addresses.
InetAddress
address=InetAddress.getByName(³hostname´);
Returns an Inetaddress object that encapsulates thesequence of four bytes
like 132.163.4.104.
To access the bytes use getAddress method
Byte[] addressbytes=address.getAddress();
9
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 10/33
10
Java Mail Messaging System
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 11/33
11
E-Mail Messaging System
Java e-mail messaging system is composed of mail
clients and mail servers.
An e-mail client is a GUI based application installed onuser¶s machine. The most popular are netscapecommunication and MS outlook.
An e-mail server is responsible for routing messages to
their destination and also storing messages until theuser receives them:
SMTP defines the process for sending e-mail in a reliableand efficient manner.
POP3 defines mechanism for retrieving messages from a
mail server. The POP3 protocol identifies the user andthe password and retrieves only those messages for thegiven user.
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 12/33
12
Process of E-Mail Transmission
E-mail Sender
E-mail Recipient
SMTP Server
POP3 Server
messages
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 13/33
13
Anatomy of an E-mail Message
An e-mail message is composed of two major sections.Headers containing a set of attributes and body( content).
The header contains the information about the message, suchas the sender, recipient, subject and time stamp.
The actual content of the message is contained in the bodypart.
Message
HeaderAttributes
Content(Body)
Sender, recipient, subject
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 14/33
14
Electronic MailThree major components:
user agents
mail servers
simple mail transferprotocol: SMTP
User Agent
composing, editing, readingmail messages
e.g: Outlook, elm, NetscapeMessenger
outgoing, incomingmessages stored on server
user mailbox
outgoingmessage queue
mailserver
useragent
useragent
useragent
server
useragent
useragent
mailserver
useragent
SMTP
SMTP
SMTP
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 15/33
15
Electronic Mail: mail servers
Mail Servers
mailbox containsincoming messages foruser
message queue of outgoing (to be sent)mail messages
SMTP protocol betweenmail servers to send
email messages client: sending mail
server
³server´: receivingmail server
mailserver
useragent
useragent
user
agent
server
useragent
useragent
mailserver
useragent
SMTP
SMTP
SMTP
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 16/33
16
Electronic Mail: SMTP uses TCP to reliably transfer email message from
client to server, port 25
direct transfer: sending server to receiving server
three phases of transfer
handshaking (greeting)
transfer of messages
closure
command/response interaction
commands: ASCII text response: status code and phrase
messages must be in 7-bit ASCII
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 17/33
17
Scenario: A sends message to B
1) A uses UA to composemessage and providesB¶s Email addressb@@bits-pilani.ac.in
2) A¶s UA sends message toher mail server;message placed inmessage queue
3) Client side of SMTPopens TCP connectionwith B¶s mail server
4) SMTP client sends A¶smessage over the TCPconnection
5) B¶s mail server placesthe message in Bob¶smailbox
6) Bob invokes his useragent to read message
useragent
mailserver
mailserver user
agent
1
2 3 4 56
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 18/33
18
Try SMTP interaction for yourself:
telnet servername 25
see 220 reply from server
enter HELO, MAIL FROM, RCPT TO, DATA, QUIT
commands
above lets you send email without using emailclient (reader)
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 19/33
19
Sample SMTP interactionS: 220 bitsmail01.bits-pilani.ac.inC: HELO bitsmail01.bits-pilani.ac.in
S: 250 Hello bitsmail01.bits-pilani.ac.in, pleased to meet you
C: MAIL FROM : < [email protected] >
S: 250 r [email protected]... Sender ok
C: R CPT TO: < [email protected]>
S: 250 [email protected] ... Recipient ok
C: DA T A
S: 354 Enter mail, end with "." on a line by itself
C: Do you like ketchup?
C: How about pickles?
C: . S: 250 Message accepted for delivery
C: QUIT
S: 221 bitsmail01.bits-pilani.ac.in closing connection
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 20/33
Java Mail API
The JavaMailAPI provides classes thatmodel a mail system.
Java Mail API is a simple and handy toolfor implementing mail/messagingfunctionality in your applications.
The JavaMail API provides a set of
abstract classes that model a mailsystem. The API provides a platformindependent and protocol independentframework to build Java technology-based
mail and messaging applications20
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 21/33
Core classes of this API are
javax.mail.Session, javax.mail.Store,
javax.mail.Transport, javax.mail.Folder, and javax.mail.Message.
21
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 22/33
javax.mail.Session
The javax.mail.Session class is thetop-level entry class for the Java Mail
API, and its most commonly usedmethods provide the ability to controland load the classes that representthe service provider implementations
(SPI) for various mail protocols
22
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 23/33
javax.mail.Store
The javax.mail.Store class isimplemented by a service provider,
such as a POP Mail implementationdeveloper, and allows for read, write,monitor, and search access for aparticular mail protocol.
23
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 24/33
javax.mail.Transport
The javax.mail.Transport class isanother provider-implemented class
and is used for sending a messageover a specific protocol.
24
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 25/33
javax.mail.Folde
The javax.mail.Folder class isimplemented by a provider; it gives
hierarchical organization to mailmessages and provides access to e-mail messages in the form of
javax.mail.Message class objects
25
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 26/33
javax.mail.Message
The javax.mail.Message class isimplemented by a provider and
models all the details of an actual e-mail message, such as the subjectline, sender/recipient e-mail address,sent date, and so on
26
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 27/33
27
Example Program
import javax.mail.*;import javax.mail.internet.*;
public class QuickMailText {
/*** Sends a simple text e-mail message.*
* @param smtpHost name of the SMTP mail server* @param from e-mail address of the sender* @param to e-mail address of the recipient* @param subject subject of the e-mail message* @param messageText the actual text of the message** @throws javax.mail.MessagingFormatException problems
sending message*/public static void sendMessage(String smtpHost,String from, String to,String subject, String messageText)throws MessagingException {
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 28/33
28
Step 1: Configure the mail session
System.out.println("Configuring mail session for: " +smtpHost);
java.util.Properties props = new java.util.Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", " mail.itmindia.edu ");
props.setProperty("mail.user", "emailuser");Session mailSession =Session.getDefaultInstance(props);
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 29/33
Step 2: Construct the message
System.out.println("Constructing message - from=" +from + " to=" + to);
InternetAddress fromAddress = newInternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);MimeMessage testMessage = newMimeMessage(mailSession);
testMessage.setFrom(fromAddress);testMessage.addRecipient(javax.mail.Message.RecipientT
ype.TO, toAddress);
testMessage.setSentDate(new java.util.Date());testMessage.setSubject(subject);testMessage.setText(messageText);System.out.println("Message constructed");
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 30/33
Step 3: Now
send the message
Transport transport =
mailSession.getTransport();transport.connect();
transport.send(testMessage);
System.out.println("Messagesent!");
}
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 31/33
31
public static void main(String[] args) {if (args.length != 3) {System.out.println("Usage: java QuickMailText <smtphost> <from>
<to>");
System.exit(1);}
String smtpHost = args[0];String from = args[1];String to = args[2];String subject = "Test Message - quickmail_text";StringBuff er theMessage = new StringBuff er();
theMessage.append("H
ello,\
n\
n");theMessage.append("Hope all is well.\n");theMessage.append("Cheers!");try {QuickMailText.sendMessage(smtpHost, from, to, subject,
theMessage.toString());}catch (javax.mail.MessagingException exc) {
exc.printStackTrace();}
}}
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 32/33
32
R unning Java Mail API Programs(A) Sending E-Mail
---------------
c:\>java <programname> <smtphost> <from> <to>
OR
java <programname> <smtphost> <from> <to> <f iletoattach>
For example,
java QuickMailText mail.itmindia.edu [email protected] [email protected]
OR
java QuickMailAttach mail.itmindia.edu [email protected] [email protected]
8/6/2019 Lect-5 Java Emailing
http://slidepdf.com/reader/full/lect-5-java-emailing 33/33
33
(B) R etrieving all E-Mails
c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90
<programname> <pop3host> <user> <password>
For example,
c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90MessageList 192.168.0.1 rimpy abc
(C) Viewing Message Contents of an E-Mail-------------------------------------
c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90<programname> <pop3host><user> <password> <messagenumber>
For example,
c:\>java -Dhttp.proxyHost=192.168.0.1 -Dhttp.proxyPort=90MessageView 192.168.0.1 rimpy abc 2