使用java发送电子邮件而不使用JavaMail

时间:2012-02-10 23:21:24

标签: java sockets smtp

我想编写一个套接字程序来发送SMTP电子邮件,而不使用任何JavaMail API。我在互联网上找到了代码,但它无法正常工作。 这是该计划:

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


public class SMTPTest
{ public static void main(String[] args)
{ SMTPTest smtp = new SMTPTest();
smtp.sendMail();
}

public void sendMail()
{
try
{
Socket s = new Socket("smtp.gmail.com", 465); 
out = new PrintWriter(s.getOutputStream());
in = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String hostName = InetAddress.getLocalHost().getHostName();
System.out.println("hostName = " + hostName);
send(null);
send("HELO " + hostName);
send("MAIL FROM: " + "my email@gmail.com");
send("RCPT TO: " + "my email@gmail.com");
send("DATA");
send("Happy SMTP Programming!!");
send("Happy SMTP Programming!!");
send(".");
send("QUIT");
s.close();
out.close();
in.close();
}
catch(IOException e)
{ e.printStackTrace();
}
}

public void send(String s) throws IOException
{ if (s != null)
{ out.println(s);
out.flush();
}
String line;
if ((line = in.readLine()) != null) //output the response
System.out.println(line);
}

private PrintWriter out;
private BufferedReader in;
}

任何人都可以提供帮助吗? 这是错误:

java.net.UnknownHostException: smtp.gmail.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at SMTPTest.sendMail(SMTPTest.java:19)
at SMTPTest.main(SMTPTest.java:12) 

2 个答案:

答案 0 :(得分:0)

  

您无法使用普通SMTP的Google邮件服务器 - 他们需要TLS。

不确定这是否有帮助,但我在一些代码示例中看到了这个陈述:

System.setProperty("mail.smtp.starttls.enable","true");
Socket s = new Socket(...);

答案 1 :(得分:0)

使用SSLSocket代替Socket,如下所示:

SSLSocket socket = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(InetAddress.getByName("smtp.gmail.com"), 465);

你必须抓住异常,但你明白了。