Send email using java without JavaMail

别等时光非礼了梦想. 提交于 2019-12-24 13:24:49

问题


I want to write a socket program to send a SMTP email, without using any JavaMail API. I found code on the Internet to do that, but it doesn't work correctly. Here's the program:

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;
}

Can anyone can help? Here is the error:

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) 

回答1:


You cannot use Google mail servers with plain SMTP - they need TLS.

Not sure if this will help, but I've seen this statement in some code examples:

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



回答2:


Instead of Socket, use SSLSocket, like so:

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

You'll have to catch the exception, but you get the idea.



来源:https://stackoverflow.com/questions/9236224/send-email-using-java-without-javamail

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!