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 接受这种类型的邮件。