I am able to connect to smtp.gmail.com via port 465. After using the AUTH LOGIN command receive a 334 VXNlcm5hbWU6 which when decoded is "Username:"
I can't seem to figure out how to send my username over the server. I am encoding the username and sending, but getting no reply. The next reply should be to ask for my Password.
See below:
public class MailComponent{
Socket socket = null;
final static String MAIL_SERVER = "smtp.gmail.com";
final static int SMTP_PORT = 465;
String uName = "[email protected]";
String encodedName = Base64.getEncoder().encodeToString(uName.getBytes(StandardCharsets.UTF_8));
public MailComponent(){ /*Create constructor later*/}
public void sendMail() throws Exception{
try{
// Establish TCP Connection With Mail Server
socket = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(MAIL_SERVER, SMTP_PORT);
// Create a Buffered Reader to read one line at a time
InputStream inStream = socket.getInputStream();
InputStreamReader inReader = new InputStreamReader(inStream);
BufferedReader bReader = new BufferedReader(inReader);
// Read Server's Greeting
String serverResponse = bReader.readLine();
System.out.println("Server Greeting: " + serverResponse);
if (!serverResponse.startsWith("220")){
throw new Exception("220 Reply Not Received From Server!");
}
// Reference socket's output stream
OutputStream oStream = socket.getOutputStream();
// Send HELO command
String heloCommand = "HELO smtp.gmail.com\r\n";
oStream.write(heloCommand.getBytes("US-ASCII"));
serverResponse = bReader.readLine();
System.out.println("HELO Response: " + serverResponse);
if (!serverResponse.startsWith("250"))
throw new Exception("250 Reply Not Received From Server!");
// Obtain Authorization
String authCommand = "AUTH LOGIN\r\n";
oStream.write(authCommand.getBytes("US-ASCII"));
serverResponse = bReader.readLine();
System.out.println("Auth Response: " + serverResponse);
// Give Username
oStream.write(encodedName.getBytes(StandardCharsets.UTF_8));
serverResponse = bReader.readLine();
System.out.println("Username Response: " + serverResponse);
Everything seems to work fine, but I don't receive any reply once I send my username. Any ideas on why this might be?
Once asked for the username, you must send it encoded as well as sending the CR/LF as Dmitry Streblechenko added in his last comment. However, If you send a username along with the CL/LF the server will think it is part of the username or password and continue waiting for client response. I got it to work by simply sending both in separate messages.
As a note: The STARTTLS command wasn't necessary as I am using SSL.