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(公司邮件服务器)服务器主机名,以及我公司邮件服务器的userid和pwd(以smtp主机的形式提供)...
有了这些,我发送邮件作为GMail用户,
但是为什么GMAIL会接受这种类型的邮件。
答案 0 :(得分:6)
您已经发现了为什么会有垃圾邮件。 : - )
您通过公司的邮件服务器发送邮件。您公司的邮件服务器似乎没有检查您使用的发件人地址是否对您的邮件服务器有效,因此它允许您使用您的Gmail地址而不是您的公司地址。不,它不会检查Gmail以确定它是否正常。
答案 1 :(得分:0)
Gmail无法在未经任何身份验证的情况下发送邮件。
您无法使用错误的凭据进行身份验证。换句话说,如果您有密码(并且gmail需要密码),您无法在不发送密码的情况下登录,因此您将无法发送任何密码。
一般来说,你可以,当然。在您的具体示例代码中,您使用的是GMail,它不允许匿名发送。
从他们的参考文献:
smtp.gmail.com(使用身份验证) 使用身份验证:是的 TLS / STARTTLS的端口:587 SSL端口:465
关于您的catch子句的其他评论:
在我看来,你严重滥用了这个例外的想法。更好的方法是:
catch(Exception x)
{
var s = x.Message;
if ( x.InnerException!=null )
{
s += Environment.NewLine + x.InnerException.Message;
}
MessageBox.Show(s);
}