簡體   English   中英

在 c# 中發送 email

[英]send email in c#

我嘗試使用此代碼發送 email.. 但在smtp.Send(mail)中發生錯誤; 消息“發送郵件失敗”

  MailMessage mail = new MailMessage();
  // set the addresses
  mail.From = new MailAddress("from@gmail.com");

  mail.To.Add(new MailAddress("to@yahoo.com"));

  // set the content
  mail.Subject = "test sample";
  mail.Body = @"thank you";
  SmtpClient smtp = new SmtpClient("smtp.gmail.com");

  smtp.Credentials = new NetworkCredential("from@gmail.com", "password"); 
  smtp.Send(mail);

在您的代碼中指定端口號:

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587)

還要查看此線程, 使用C#通過Gmail SMTP服務器發送電子郵件

您需要為gmail設置smtp.EnableSsl = true

看一看這個課程,它應該對您有用:

public class Email
{
    NetworkCredential credentials;
    MailAddress sender;

    public Email(NetworkCredential credentials, MailAddress sender)
    {
        this.credentials = credentials;
        this.sender = sender;
    }

    public bool EnableSsl
    {
        get { return _EnableSsl; }
        set { _EnableSsl = value; }
    }
    bool _EnableSsl = true;

    public string Host
    {
        get { return _Host; }
        set { _Host = value; }
    }
    string _Host = "smtp.gmail.com";

    public int Port
    {
        get { return _Port; }
        set { _Port = value; }
    }
    int _Port = 587;

    public void Send(MailAddress recipient, string subject, string body, Action<MailMessage> action, params FileInfo[] attachments)
    {
        SmtpClient smtpClient = new SmtpClient();

        // setup up the host, increase the timeout to 5 minutes
        smtpClient.Host = Host;
        smtpClient.Port = Port;
        smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = credentials;
        smtpClient.Timeout = (60 * 5 * 1000);
        smtpClient.EnableSsl = EnableSsl;

        using (var message = new MailMessage(sender, recipient)
        {
            Subject = subject,
            Body = body
        })
        {
            foreach (var file in attachments)
                if (file.Exists)
                    message.Attachments.Add(new Attachment(file.FullName));
            if(null != action)
                action(message);
            smtpClient.Send(message);
        }
    }
}

填寫mail.Host和mail.Port

具有適當值的屬性

創建新的MailMessage時,應該使用using語句,以及一些您錯過的東西,例如端口號和enableSSL

using (MailMessage mail = new MailMessage())
{
    mail.From = new MailAddress("from@gmail.com");
    mail.To.Add(new MailAddress("to@yahoo.com"));
    mail.Subject = "test sample";
    mail.Body = @"thank you";

    SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
    smtpServer.Port = 587;
    smtpServer.Credentials = new NetworkCredential("from@gmail.com", "password"); 
    smtpServer.EnableSsl = true;
    smtpServer.Send(mail);
}

這是我前一段時間寫的一個基本的GMAIL smtp電子郵件實現:

public static bool SendGmail(string subject, string content, string[] recipients, string from)
{
    bool success = recipients != null && recipients.Length > 0;

    if (success)
    {
        SmtpClient gmailClient = new SmtpClient
        {
            Host = "smtp.gmail.com",
            Port = 587,
            EnableSsl = true,
            UseDefaultCredentials = false,
            Credentials = new System.Net.NetworkCredential("******", "*****") //you need to add some valid gmail account credentials to authenticate with gmails SMTP server.
        };


        using (MailMessage gMessage = new MailMessage(from, recipients[0], subject, content))
        {
            for (int i = 1; i < recipients.Length; i++)
                gMessage.To.Add(recipients[i]);

            try
            {
                gmailClient.Send(gMessage);
                success = true;
            }
            catch (Exception) { success = false; }
        }
    }
    return success;
}

它對您來說應該可以正常工作,但是您需要在代碼中標記的地方添加一個有效的gmail acocunt。

這是我檢查過的發送郵件的功能...並且工作正常。

`

        private static bool testsendemail(MailMessage message)
        {

            try

            {

            MailMessage message1 = new MailMessage();

            SmtpClient smtpClient = new SmtpClient();

            string msg = string.Empty;

            MailAddress fromAddress = new MailAddress("FromMail@Test.com");
            message1.From = fromAddress;
            message1.To.Add("ToMail@Test1.com");
            message1.Subject = "This is Test mail";
            message1.IsBodyHtml = true;
            message1.Body ="You can write your body here"+message;
            smtpClient.Host = "smtp.mail.yahoo.com"; // We use yahoo as our smtp client
            smtpClient.Port = 587;
            smtpClient.EnableSsl = false;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new  System.Net.NetworkCredential("SenderMail@yahoo.com", "YourPassword");

            smtpClient.Send(message1);
        }
        catch
        {
            return false;
        }
        return true;

    }`           

謝謝。

以下是Gmail服務的C#代碼

using System;
using System.Net;
using System.Net.Mail;

namespace EmailApp
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            String SendMailFrom = "Sender Email";
            String SendMailTo = "Reciever Email";
            String SendMailSubject = "Email Subject";
            String SendMailBody = "Email Body";

            try
            {
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com",587);
                SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
                MailMessage email = new MailMessage();
                // START
                email.From = new MailAddress(SendMailFrom);
                email.To.Add(SendMailTo);
                email.CC.Add(SendMailFrom);
                email.Subject = SendMailSubject;
                email.Body = SendMailBody;
                //END
                SmtpServer.Timeout = 5000;
                SmtpServer.EnableSsl = true;
                SmtpServer.UseDefaultCredentials = false;
                SmtpServer.Credentials = new NetworkCredential(SendMailFrom, "Google App Password");
                SmtpServer.Send(email);

                Console.WriteLine("Email Successfully Sent");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }

        }
    }
}

供參考: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html

暫無
暫無

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

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