加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用SmtpClient时“操作超时”

发布时间:2020-12-15 08:40:33 所属栏目:百科 来源:网络整理
导读:我正在尝试使用C#框架创建一个小应用程序来发送电子邮件.但是,它不起作用.该应用程序总是给我“操作超时”.我不是为什么. 这是我的代码: private void button1_Click(object sender,EventArgs e) { MailAddress fromAddress = new MailAddress("from@gmail.
我正在尝试使用C#框架创建一个小应用程序来发送电子邮件.但是,它不起作用.该应用程序总是给我“操作超时”.我不是为什么.

这是我的代码:

private void button1_Click(object sender,EventArgs e)
   {
     MailAddress fromAddress = new MailAddress("from@gmail.com");
     MailAddress toAddress = new MailAddress("to@gmail.com");

     MailMessage mail = new MailMessage(fromAddress.Address,toAddress.Address);
     mail.Subject = "Testing";
     mail.Body = "contents.";

     SmtpClient client = new SmtpClient();
     client.Host = "smtp.gmail.com";
     client.Port = 587;
     client.EnableSsl = true;
     client.Timeout = 100;
     client.UseDefaultCredentials = false;
     client.Credentials = new NetworkCredential("username","password");

     try
        {
            client.Send(mail);
            MessageBox.Show("Mail Sent!","Success",MessageBoxButtons.OK);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK);
        }

    }

谢谢!

解决方法

尝试设置更高的超时限制.它是以毫秒为单位.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;

namespace GmailSendTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender,EventArgs e)
        {
            MailAddress fromAddress = new MailAddress("myusername@gmail.com");
            MailAddress toAddress = new MailAddress("myusername@gmail.com");

            MailMessage mail = new MailMessage(fromAddress.Address,toAddress.Address);
            mail.Subject = "Testing";
            mail.Body = "contents.";

            SmtpClient client = new SmtpClient();
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.EnableSsl = true;
            client.Timeout = 10000;
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential("myusername","mypassword"); 

            try
            {
                client.Send(mail);
                MessageBox.Show("Mail Sent!",MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,MessageBoxButtons.OK);
            }
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读