public class SendMail {
private class SMTPAuthenticator extends javax.mail.Authenticator
{
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("userID", "pwd");
}
}
public void sendMail() throws Exception {
String strFromIds = "xyz@gmail.com";
String strToIds = "xyz@domain.com";
String strSubject = "Sample Mail Subject.";
String strContent = "Sample Mail Content";
Properties objProperties = System.getProperties();
objProperties.put("mail.smtp.host", "<smtp host name>");
objProperties.put("mail.smtp.port", "25");
objProperties.put("mail.transport.protocol", "smtp");
objProperties.put("mail.smtp.submitter", "<user id>");
objProperties.put("mail.smtp.auth", true);
objProperties.put("mail.debug", "true");
Session objSMTPSession = Session.getDefaultInstance(objProperties, new
SMTPAuthenticator());
Message objMessage = new MimeMessage(objSMTPSession);
objMessage.setFrom(new InternetAddress(strFromIds));
InternetAddress[] objToAddress = new InternetAddress[1];
objToAddress[0] = new InternetAddress(strToIds);
objMessage.setRecipients(Message.RecipientType.TO, objToAddress);
objMessage.setSubject(strSubject);
Multipart objMultiPart = new MimeMultipart();
MimeBodyPart objBodyPart = new MimeBodyPart();
objBodyPart.setText(strContent);
objMultiPart.addBodyPart(objBodyPart);
objMessage.setContent(objMultiPart);
Date objSentDate = new Date();
objMessage.setSentDate(objSentDate);
Transport.send(objMessage);
objMessage = null;
}
public static void main(String[] args) {
try {
new SendMail().sendMail();
} catch (Exception ex) {
System.out.println("Exception in main :: " + ex);
}
}
}
通过使用上面的代码,我可以使用 GMail 邮件 ID(例如:xyz@gmail.com)的发件人地址向 gmail 用户发送邮件,而无需提供 gmail id 的身份验证详细信息,
这里我给出了我的 smtp(公司邮件服务器)服务器主机名,以及我公司邮件服务器的用户 ID 和密码(作为 smtp 主机给出)...
有了这些,我将以 GMail 用户身份发送邮件,
但为什么 GMAIL 接受这种类型的邮件。
最佳答案
您已经发现为什么会有垃圾邮件。 :-)
您正在通过公司的邮件服务器发送邮件。您公司的邮件服务器似乎没有检查您使用的发件人地址是否对您的邮件服务器有效,因此它允许您使用 Gmail 地址而不是公司地址。不,它不会检查 Gmail 以确定是否正常。
关于java - 为什么 GMail 接受未经身份验证发送邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14559348/