如何在C#中发送电子邮件? [英] How can I send email in C#?

查看:80
本文介绍了如何在C#中发送电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MailMessage mail = new MailMessage();
     mail.From = new MailAddress("from@gmail.com");
     mail.To.Add("to@gmail.com");
     mail.Subject = "Hello World";
     mail.Body = "<h1>Hello</h1>";
     mail.IsBodyHtml = true;
     mail.Attachments.Add(new Attachment("C:\\report.txt"));

     using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
     {
         smtp.Credentials = new System.Net.NetworkCredential("from@gmail.com", "password");
         smtp.EnableSsl = true;
         smtp.Send(mail);
         MessageBox.Show("Message sent");
     }





我尝试过:



以上代码在我自己的笔记本电脑上运行良好,但是当我在联网PC中使用它时(作为一个简单的用户,而不是管理员),

我遇到了这个错误



What I have tried:

Above code worked fine in my own laptop, but when I used it in networked PC (as a simple user, not admin),
I faced this error

ystem.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 64.233.162.109:587

推荐答案

你的代码看起来很好,它应该发送电子邮件(当然,应该连接到服务器),你尝试连接默认的TCP端口用于SMTP通信?那是25,考虑尝试一下,

Your code looks fine to me, and it should send the email (and of course, should connect to the server), did you try connecting through the default TCP port for SMTP communication? That is 25, consider trying that one out,
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 25))

除此之外,只需考虑几件事:



1)gmail设置中是否启用了SMTP?

2)防火墙是否阻塞您从应用程序到该IP地址/端口的通信。这真的很重要。

3)Google允许您的帐户进行通信,有时我也发现Google不允许特定应用程序使用SMTP服务。



除此之外,我们可以研究的更少。还有一件事,请尝试连接到Outlook或Yahoo!帐户并查看它们是否正常工作 - 代码看起来很好



通过.NET框架发送电子邮件和一般问题 - 使用C#代码 [ ^ ]。

Other than that, only a few things to consider:

1) Is SMTP enabled in the gmail settings?
2) Is firewall blocking your communication to that IP address/port from your application. This can really matter a lot.
3) Is Google permitting your account to communicate, sometimes I have also found that Google doesn't allow specific applications to use SMTP services.

Other than that, there is very less we can look into. One more thing, kindly try to connect to Outlook or Yahoo! accounts and see if they are working — code looks fine.

Sending emails over .NET framework, and general problems – using C# code[^].


这篇关于如何在C#中发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆