簡體   English   中英

通過Gmail主機和端口發送電子郵件

[英]Send Email WIth Gmail Host And Port

我想通過Gmail發送電子郵件,但出現以下異常

嘗試對無法訪問的網絡進行套接字操作[2a00:1450:400c: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);

加:

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

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

(摘自《我如何使SMTP在C#中進行身份驗證》

嘗試這個

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);
  }

我這樣做是這樣的:

這些用法:

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());
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM