我尝试了两个应用程序,一个在java中,一个在C#中。 Java应用程序可以成功发送电子邮件,但C#不能。下面是两个应用: 1.JavaSmtpClient无法发送电子邮件
final String username = "[email protected]";
final String password = "mypassword";
String smtpHost = "smtp.mydomain";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(username));
message.setSubject("Test send email");
message.setText("Hi you!");
Transport.send(message);
2.C#
string username = "[email protected]";
string password = "mypassword";
string smtpHost = "smtp.mydomain";
SmtpClient mailClient = new SmtpClient(smtpHost, 465);
mailClient.Host = smtpHost;
mailClient.Credentials = new NetworkCredential(username, password);
mailClient.EnableSsl = true;
MailMessage message = new MailMessage(username, username, "test send email", "hi u");
mailClient.Send(message);
那么,什么是我在C#应用程序发出的错误呢?为什么它不能发送电子邮件?
编辑: 我已阅读这个问题How can I send emails through SSL SMTP with the .NET Framework?它的工作原理。不推荐使用System.Web.Mail.SmtpMail,但System.Net.Mail.SmtpClient不适用。为什么?
3,本C#代码做工精细:
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver","smtp.mydomain");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport","465");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing","2");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "[email protected]");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "mypassword");
myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
myMail.From = "[email protected]";
myMail.To = "[email protected]";
myMail.Subject = "new code";
myMail.BodyFormat = System.Web.Mail.MailFormat.Html;
myMail.Body = "new body";
System.Web.Mail.SmtpMail.SmtpServer = "smtp.mydomain:465";
System.Web.Mail.SmtpMail.Send(myMail);
你会得到什么样的错误? – Mathew
如果我使用代理,它会抛出“无法连接,因为目标机器主动拒绝它[serverip]:465”。如果我不使用代理,它会抛出“操作超时。”。这两个Java应用程序都可以工作。 – hieund