[英]Sending email with Java
下面是我编写的使用Java发送电子邮件的简单测试类。 我正在尝试从本地主机发送消息。 但是我收到以下错误消息:
javax.mail.MessagingException: Unknown SMTP host: http://localhost:8080/;
nested exception is:
java.net.UnknownHostException: http://localhost:8080/
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1280)
我将主机值更改为简单的“ localhost”,但遇到了同样的问题。 有任何解决办法吗? 真正的服务器可以工作吗?
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MyEmail {
public static void main(String... args) {
String to = "me@email.com";
String from = "other@email.com";
String host = "http://localhost:8080/";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host",host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("This is a subject");
message.setText("The text is what it is the text");
Transport.send(message);
System.out.println("Successful");
}catch(MessagingException mx){
mx.printStackTrace();
}
}
}
主机值应该只是主机名或IP地址。 这不是HTTP。
要设置端口,请将属性mail.smtp.port
设置为您的端口号(作为字符串)
您需要在指定的主机上运行邮件(SMTP)服务器,以发送任何邮件。 主机对应于SMTP服务器的地址(不带http://),端口对应于已配置的smtp端口。 查看您的问题,与SMTP服务器建立连接时出现问题。请确保根据正在运行的smtp服务器更正主机和端口的参数,然后重试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.