【发布时间】:2016-12-15 01:25:00
【问题描述】:
我试过用 Java 发送邮件。
- OS X
- 使用 1.7 版
我的客户使用了联系表。
我的客户希望更改“邮件发件人”。 它是从“联系表格”发送的“用户电子邮件”。 (这是欺骗邮件。但是,没问题。因为从客户服务器发送到客户邮件服务器。)
但是,我不知道在 java 中设置的信封。
我尝试了下面的java代码。
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
private static void sendMail() throws Exception {
String smtpServer = "hogehoge.smtp.server.com";
int port = "587";
String userid = "from@gmail.com";
String password = "password";
String contentType = "text/plain";
String subject = "Test Subject";
String from = "from@gmail.com";
String to = "to@gmail.com";
String bounceAddr = "from@gmail.com";
String body = "send mail";
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", smtpServer);
props.put("mail.smtp.from", bounceAddr);
Session mailSession = Session.getInstance(props);
mailSession.setDebug(true);
MimeMessage message = new MimeMessage(mailSession);
message.addFrom(InternetAddress.parse(from));
message.setRecipients(Message.RecipientType.TO, to);
message.setSubject(subject);
message.setContent(body, contentType);
Transport transport = mailSession.getTransport();
try{
System.out.println("Sending ....");
transport.connect(smtpServer, port, userid, password);
transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
System.out.println("Sending done ...");
}
catch(Exception e) {
System.err.println("Error Sending: ");
e.printStackTrace();
}
transport.close();
}
我认为通常是代码。
但是,我出错了。
503 不是您的域 (#5.5.1)
可能设置了“邮件发件人”,而不是从客户邮件服务器注册电子邮件地址。
所以,我也尝试了使用终端的 telnet。
$ printf "%s\0%s\0%s" from@gmail.com from@gmail.com password | openssl base64 -e | tr -d '\n'; echo
ZnJvbUBnbWFpbC5jb20AZnJvbUBnbWFpbC5jb20AcGFzc3dvcmQ=
$ telnet hogehoge.smtp.server.com 587
Trying xxx.xxx.xxx.xxx...
Connected to hogehoge.smtp.server.com
Escape character is '^]'.
220 smtp.server.com ESMTP
EHLO localhost // my type
250-smtp.server.com
...
250 AUTH LOGIN PLAIN CRAM-MD5
AUTH PLAIN ZnJvbUBnbWFpbC5jb20AZnJvbUBnbWFpbC5jb20AcGFzc3dvcmQ= // my type
235 ok, go ahead (#2.0.0)
MAIL FROM:<from@gmail.com> // my type
250 ok
RCPT TO:<to@gmail.com> // my type
250 ok
DATA // my type
354 go ahead
subject:Test Mail // my type
from:User Mail <spoof@gmail.com> // my type. set envelope from mail address.
to:to@gmail.com // my type
// my type
send mail. // my type
. // my type
250 ok 1481706367 qp 12070
quit // my type
221 smtp.server.com
Connection closed by foreign host.
这就成功了。
如何在 java 中设置信封,类似于上面的案例 telnet。
感谢您提供的任何帮助。
【问题讨论】:
-
我相信
mail.smtp.from是信封MAIL FROM -
这可能与您使用的 IP 地址/主机名有关。在 telnet 实验中,您使用了 localhost。邮件服务器可能会信任来自
127.0.0.1/localhost的连接来欺骗发件人而不是主机外 IP 地址。 -
你能试试吗? message.setFrom(new InternetAddress("no-reply@xxx.com", "没有回复"));和 message.setReplyTo(InternetAddress.parse("no-reply@xxx.com"));
-
感谢您的评论!我要试试看,看看。