2013-02-18 11 views
0

Здравствуйте, я работал над этим кодом, чтобы выяснить, как работает SMTP с java-программой, и я получил очень много, но я продолжаю получать эту ошибку, и я не знаю, что с этим не так. Все швы - это то, что другие подобные программы, которые я смотрел, делают, но их, похоже, работает. Он получает весь путь вниз к FROM линии, а затем выводит эту ошибкуОшибка электронной почты SMTP и Java

530 5.7.0 Must issue a STARTTLS command first. n1sm21348109bkv.14 - gsmtp 
Exception in thread "main" java.lang.Exception: 250 reply not received from server. 

at emailagent.EmailAgent.main(EmailAgent.java:73) 

Любая помощь с этим будет оценено Благодаря

import java.io.*; 
import java.net.*; 
import java.util.*; 

public class EmailAgent 
{ 
public static void main(String[] args) throws Exception 
{ 

    // Establish a TCP connection with the mail server. 
    System.out.println("Enter the mail server you wish to connect to (example: pop.gmail.com):\n"); 
    String hostName = new String(); 
    Scanner emailScanner = new Scanner(System.in); 
    hostName = emailScanner.next(); 
    Socket socket = new Socket(hostName, 25); 

    // Create a BufferedReader to read a line at a time. 
    InputStream is = socket.getInputStream(); 
    InputStreamReader isr = new InputStreamReader(is); 
    BufferedReader br = new BufferedReader(isr); 

    // Read greeting from the server. 
    String response = br.readLine(); 
    System.out.println(response); 
    if (!response.startsWith("220")) 
    { 
     throw new Exception("220 reply not received from server."); 
    } 

    // Get a reference to the socket's output stream. 
    OutputStream os = socket.getOutputStream(); 

    // Send HELO command and get server response. 
    String command = "HELO alice\r\n"; 
    System.out.print(command); 
    os.write(command.getBytes("US-ASCII")); 
    response = br.readLine(); 
    System.out.println(response); 

    if (!response.startsWith("250")) 
    { 
     throw new Exception("250 reply not received from server."); 
    } 


    // Send HELO command and get server response. 
    System.out.println("Enter the name of your mail domain (example: hotmail.com):"); 
    String heloDomain = emailScanner.next(); 
    String fullHeloCommand = "HELO " + heloDomain + "\r\n"; 
    System.out.print(fullHeloCommand); 
    os.write(fullHeloCommand.getBytes("US-ASCII")); 
    response = br.readLine(); 
    System.out.println(response); 

    if (!response.startsWith("250")) 
    { 
     throw new Exception("250 reply not received from server.\n"); 
    } 

    // Send MAIL FROM command. 
    System.out.println("Please enter your e-mail address (example: [email protected]:\n"); 
    String sourceAddress = emailScanner.next(); 
    String mailFromCommand = "MAIL FROM: <" + sourceAddress + ">\r\n"; 
    System.out.println(mailFromCommand); 
    os.write(mailFromCommand.getBytes("US-ASCII")); 
    response = br.readLine(); 
    System.out.println(response); 

    if (!response.startsWith("250")) 
    { 
     throw new Exception("250 reply not received from server.\n"); 
    } 

    // Send RCPT TO command. 
    System.out.println("Please type the destination e-mail address (example: [email protected]):\n"); 
    String destEmailAddress = new String(); 
    destEmailAddress = emailScanner.next(); 
    String fullAddress = new String(); 
    fullAddress = "RCPT TO: <" + destEmailAddress + ">\r\n"; 
    System.out.println(fullAddress); 
    os.write(fullAddress.getBytes("US-ASCII")); 
    response = br.readLine(); 
    System.out.println(response); 

    if(!response.startsWith("250")) 
    { 
     throw new Exception("250 reply not received from server.\n"); 
    } 

    // Send DATA command.  
    String dataString = new String(); 
    dataString = "DATA"; 
    System.out.println(dataString); 
    os.write(dataString.getBytes("US-ASCII")); 
    response = br.readLine(); 

    if(!response.startsWith("354")) 
    { 
     throw new Exception("354 reply not received from server.\n"); 
    } 

    System.out.println(response); 


    // Send message data. 
    System.out.println("Enter your message, enter '.' on a separate line to end message data entry:\n"); 
    String input = new String(); 
    while(input.charAt(0) != '.') 
    { 
     input = emailScanner.next(); 
     os.write(input.getBytes("US-ASCII")); 
    } 
     //End with line with a single period. 
    os.write(input.getBytes("US-ASCII")); 
    response = br.readLine(); 
    System.out.println(response); 

    if(!response.startsWith("250")) 
    { 
     throw new Exception("250 reply not received from server\n"); 
    } 


    // Send QUIT command. 
    String quitCommand = new String(); 
    quitCommand = "QUIT"; 
    os.write(quitCommand.getBytes("US-ASCII")); 

    } 
    } 

ответ

1

Почтовый сервер вы пытаетесь подключиться требует вы устанавливаете безопасное соединение (TLS) для использования почтовых служб. Это ошибка, которую вы получаете.

Что касается решения, я бы очень рекомендовал использовать JavaMail library, поскольку он обеспечивает большую часть этой функциональности из коробки и был прочно протестирован «в дикой природе».

+0

Я вижу, моя цель состоит в том, чтобы попытаться выяснить, как работают smtp и TCP, не вникая в специфику языка. – MNM

+0

Нет проблем, мы все были там. Я бы рекомендовал использовать почтовый сервер, для которого не требуется TLS или SSL, так как рукопожатия безопасности добавляют много сложностей. По мере того, как вы получите более удобный протокол, вы можете перейти к более продвинутым аспектам. – Perception

+0

Вы могли бы предложить почтовый сервер, который не нуждается в TLS или SSL, чтобы у меня было ощущение, что это сработало? – MNM

Смежные вопросы