使用Gmail主机和端口发送电子邮件

时间:2013-06-04 13:12:27

标签: c# asp.net email

我想通过Gmail发送电子邮件,但我收到以下异常

  

尝试对无法访问的网络进行套接字操作   [2A00:1450:400℃:C05 :: 6D]:465

你知道如何解决它吗?

MailMessage msg = new MailMessage();
msg.From = new MailAddress("test@yahoo.com");
msg.To.Add("test@yahoo.com");
msg.Subject = this.txtSubject.Text;
msg.Body = this.txtBody.Text;

SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 465;
client.EnableSsl = true;
client.Send(msg);

3 个答案:

答案 0 :(得分:0)

添加:

NetworkCredential basicCredential = 
    new NetworkCredential("username", "password"); 

smtpClient.Host = "mail.mydomain.com";
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;

(从How can I make SMTP authenticated in C#采用)

答案 1 :(得分:0)

试试这个

using System.Net;

using System.Net.Mail;

 var fromAddress = new MailAddress("from@gmail.com", "From Name");
 var toAddress = new MailAddress("to@test.com", "To Name");
 const string fromPassword = "fromPass";
const string subject = "Subject";
const string body = "Body";

 var smtp = new SmtpClient
       {
           Host = "smtp.gmail.com",
           Port = 587,
           EnableSsl = true,
           DeliveryMethod = SmtpDeliveryMethod.Network,
           UseDefaultCredentials = false,
           Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
       };
  using (var message = new MailMessage(fromAddress, toAddress)
                 {
                     Subject = subject,
                     Body = body
                 })
   {
smtp.Send(message);
  }

答案 2 :(得分:0)

我这样做了:

通过这些使用:

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;

这个按钮事件

 private void sendmail_Click(object sender, EventArgs e)
    {
        try
        {

            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("blabla@gmail.com");
            mail.To.Add("mom@gmail.com");
            mail.Subject = "something";
            mail.Body = "text that is in the mail";
//for attachements
            System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(str);
            mail.Attachments.Add(attachment);
//end attachement

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential"username from gmail", "password from gmail");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);
            MessageBox.Show("Mail Send");
            this.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }