Overview
This article will demonstrate how to communicate with smtp servers in Java using Secure iNet Factory.
Code Example
Download SMTPEx.java
01 import com.jscape.inet.email.EmailMessage;
02 import com.jscape.inet.mime.MimeException;
03 import com.jscape.inet.smtp.*;
04
05 public class SMTPEx extends SmtpAdapter
06 {
07 Smtp smtp = null;
08
09 public SMTPEx(String server)
10 {
11 smtp = new Smtp(server);
12 smtp.addSmtpListener(this);
13 }
14
15 public void openConnection() throws SmtpException
16 {
17 smtp.connect();
18 }
19
20 public void closeConnection() throws SmtpException
21 {
22 smtp.disconnect();
23 }
24
25 public void setConnectionTimeout(int timeout) throws SmtpException
26 {
27 smtp.setConnectTimeout(timeout);
28 }
29
30 public void login(String username, String password, boolean useCramMD5) throws SmtpException
31 {
32 if (useCramMD5 == false) smtp.login(username, password);
33 else smtp.login(username, password, Smtp.AUTH_CRAM_MD5);
34 }
35
36 public String issueCommand(String command) throws SmtpException
37 {
38 return smtp.issueCommand(command);
39 }
40
41 public void sendEmailMessage(String to, String from, String subject, String body) throws SmtpException, MimeException
42 {
43 smtp.send(new EmailMessage(to, from, subject, body));
44 }
45
46 public static void main(String[] args)
47 {
48 try
49 {
50 SMTPEx ex = new SMTPEx("server");
51 // open connection
52 ex.openConnection();
53 // authenticate with username and password
54 ex.login("username", "password", true);
55 // issue command and get response
56 String response = ex.issueCommand("HELO 10.0.0.1");
57 // send an email message
58 ex.sendEmailMessage("to@to.com", "from@from.com", "subject", "body");
59 // close connection
60 ex.closeConnection();
61 }
62 catch (Exception e)
63 {
64 e.printStackTrace();
65 }
66 }
67 }
Lines 1-3 : Necessary import statements. Lines 11-12 : Create Smtp instance and register an adapter. Lines 15-25 : Methods to handle events from SmtpAdapter. Lines 25-28 : Set connection timeout. Lines 30-34 : Login to the server using a username and password. Lines 36-39 : Issue a command to the server. Lines 41-44 : Send an email message.
A list of SMTP commands can be found here Go here to read more about the SMTP protocol.
|
Comments