我需要使用 SSL (SMTPS) 和身份验证发送电子邮件。然而,在 apache Commons Net 中似乎有 AuthenticatingSMTPClient(没有 SSL,虽然它扩展了 SMTPSClient?)或 SMTPSClient(没有身份验证?),我需要两者的组合(SSL + 身份验证)。任何人都知道我该怎么做?谢谢!
问问题
885 次
1 回答
4
我知道现在回复这个为时已晚,但为了其他人的未来参考,AuthenticatingSMTPClient
确实提供ssl + authentication
,因为它正在扩展SMTPSClient.
下面是示例代码,必须在我用数字(例如//1
)注释的地方进行修改。
代码:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.io.Util;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient.AUTH_METHOD;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
public final class SMTPMail
{
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException
{
String sender, recipient, subject, filename, server;
List<String> ccList = new ArrayList<String>();
FileReader fileReader = null;
Writer writer;
SimpleSMTPHeader header;
AuthenticatingSMTPClient client;
server = "<smtp server>"; // 1
try
{
sender = "<your user name>"; // 2
recipient = "<recipient>"; // 3
subject = "<mail subject>"; // 4
header = new SimpleSMTPHeader(sender, recipient, subject);
filename = "hello.txt"; //This will be the body of your mail //5
try
{
fileReader = new FileReader(filename);
}
catch (FileNotFoundException e)
{
System.err.println("File not found. " + e.getMessage());
}
client = new AuthenticatingSMTPClient("TLS", false);
client.addProtocolCommandListener(new PrintCommandListener(
new PrintWriter(System.out), true));
client.connect(server);
if (!SMTPReply.isPositiveCompletion(client.getReplyCode()))
{
client.disconnect();
System.err.println("SMTP server refused connection.");
System.exit(1);
}
client.login("hostname.testing.smtp.api"); //6
if(client.execTLS())
{
if(client.auth(AUTH_METHOD.LOGIN, "<your user name>", "<your password>")) //7
{
client.setSender(sender);
client.addRecipient(recipient);
for (String recpt : ccList) {
client.addRecipient(recpt);
}
writer = client.sendMessageData();
if (writer != null)
{
writer.write(header.toString());
Util.copyReader(fileReader, writer);
writer.close();
client.completePendingCommand();
}
if (fileReader != null ) {
fileReader.close();
}
}
}
client.logout();
client.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
}
于 2015-06-12T19:00:34.730 回答