日期:2014-05-18  浏览次数:20833 次

.net中如何使用谷歌企业邮局发送邮件
如题,我最近换了谷歌的企业邮局来用,可是自己原来网站的邮件验证却用不了了,后来发现是谷歌企业邮局和程序的问题,我用的smtp地址是:smtp.gmail.com端口是:465
C# code
 SmtpClient _smtpClient = new SmtpClient();
        _smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
        _smtpClient.Host = email_server; ;//指定SMTP服务器
        if (email_server == "smtp.gmail.com")
        {
            _smtpClient.EnableSsl = true;
            _smtpClient.Port = 465;
        }
        _smtpClient.Credentials = new System.Net.NetworkCredential(email_user, email_password);//用户名和密码

这是部分代码,这样写没错吧,断点测试过有执行 
C# code
if (email_server == "smtp.gmail.com")
        {
            _smtpClient.EnableSsl = true;
            _smtpClient.Port = 465;
        }

这两句
但是为啥就是无法发送出邮件。。。

------解决方案--------------------
邮件问题确实很麻烦,经常看到这类帖子。建议在发送的代码中加入try,然后调试到发送地方看会不会跳到Exception。有的话。详细看看Exception里面的描述信息。
------解决方案--------------------
把465端口改成587

------解决方案--------------------
我刚做了这个,你试下
把用户名和密码改成自己的,他可以发任何邮件,带了一个附件,你不要附件就注释掉
using System.Net;
using System.Net.Mail;
 public bool ShowPost()//gmail的发送方法
{
string from = "475736732@qq.com";
string pwd = "7420861467wang";
string to = TxtTo.Text.Trim();
MailMessage mail = new MailMessage(from,to);
mail.Subject = TxtHead.Text;
mail.SubjectEncoding = System.Text.Encoding.GetEncoding("gb2312");
mail.Body = TxtBody.Text;
mail.BodyEncoding = System.Text.Encoding.GetEncoding("gb2312");
mail.IsBodyHtml = true;
string server = "";
int port = 25;
if (from.IndexOf("@gpres")!=-1 || from.IndexOf("@gmail")!=-1)
{
port = 587;
server = "smtp.gmail.com";
}
else 
{
port = 25;
string temp;
temp=from.Substring(from.LastIndexOf('@')+1);
server = "smtp." + temp;
}
SmtpClient sc = new SmtpClient(server, port);
if (port!=25)
{
sc.EnableSsl = true;
}
sc.Credentials = new NetworkCredential(from, pwd);

if(FileUpload.HasFile==true)
{
string FileName = FileUpload.FileName;
String Extend = System.IO.Path.GetExtension(FileName);
string fileurl = System.IO.Path.GetFileName(FileName);
string Dir = Server.MapPath("fujian");
Dir = Dir + "/" + fileurl;
if (Extend.ToLower() != ".exe" || Extend.ToLower() != ".html" || Extend.ToLower() != ".htm")
{
FileUpload.SaveAs(Dir);
System.Net.Mail.Attachment myAttachment = new Attachment(Dir);
myAttachment.NameEncoding = System.Text.Encoding.GetEncoding("gb2312");
mail.Attachments.Add(myAttachment);

}
else
{
Response.Write("<script>function window.onload() {alert('对不起,您上传的文件格式不正确!');window.location.href='post.aspx';}</script>");