Java Reference
In-Depth Information
}
}
}
You can actually bundle almost all these steps up into a single static method call:
Transport
.
send
(
msg
,
"username"
,
"password"
);
If you do this, the SMTP server is read from the system property mail.smtp.host.
Example 2-1
puts all these steps together into a standalone program that sends the
following message:
Date: Fri, 29 Nov 2013 15:55:42 -0500 (EST)
From: Bill Gates <god@microsoft.com>
To: elharo@ibiblio.org
Subject: You must comply.
Resistance is futile. You will be assimilated!
I've shown this message in standard RFC 822 format used for Internet email. However,
dles details of the underlying protocol.
Example 2-1. Sending a very simple mail message
import
javax.mail.*
;
import
javax.mail.internet.*
;
import
java.io.UnsupportedEncodingException
;
import
java.util.*
;
public
class
Assimilator
{
public
static
void
main
(
String
[]
args
)
{
Properties
props
=
new
Properties
();
Session
session
=
Session
.
getInstance
(
props
);
MimeMessage
msg
=
new
MimeMessage
(
session
);
Transport
t
=
null
;
try
{
Address
bill
=
new
InternetAddress
(
"god@microsoft.com"
,
"Bill Gates"
);
Address
elliotte
=
new
InternetAddress
(
"elharo@ibiblio.org"
);
msg
.
setText
(
"Resistance is futile. You will be assimilated!"
);
msg
.
setFrom
(
bill
);
msg
.
setRecipient
(
Message
.
RecipientType
.
TO
,
elliotte
);
msg
.
setSubject
(
"You must comply."
);
t
=
session
.
getTransport
(
"smtps"
);
t
.
connect
(
"smtp.gmail.com"
,
"erharold"
,
"password"
);
t
.
sendMessage
(
msg
,
msg
.
getAllRecipients
());
}
catch
(
MessagingException
|
UnsupportedEncodingException
ex
)
{