首页 >后端开发 >C++ >如何使用 .NET Framework 配置 SSL SMTP 电子邮件发送?

如何使用 .NET Framework 配置 SSL SMTP 电子邮件发送?

DDD
DDD原创
2024-10-30 01:02:04947浏览

How to Configure SSL SMTP Email Sending with the .NET Framework?

使用 .NET Framework 进行 SSL SMTP

使用 .NET Framework 通过 SSL SMTP 服务器发送电子邮件可以通过配置 SMTP 客户端来实现因此。这是分步指南:

1.创建 SmtpClient 实例:

System.Net.Mail.SmtpClient _SmtpServer = new System.Net.Mail.SmtpClient();

2.指定服务器主机和端口:

_SmtpServer.Host = "smtp.yourserver.com";
_SmtpServer.Port = 465;

3.启用 SSL:

_SmtpServer.EnableSsl = true;

4.设置凭据(可选):

_SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");

5.配置发送超时:

_SmtpServer.Timeout = 5000;

6.将 UseDefaultCredentials 设置为 False:

_SmtpServer.UseDefaultCredentials = false;

7.创建邮件消息:

MailMessage mail = new MailMessage();
mail.From = new MailAddress(from);
mail.To.Add(to);
mail.Subject = subject;
mail.Body = content;
mail.IsBodyHtml = useHtml;

8.发送电子邮件:

_SmtpServer.Send(mail);

Gmail 的 SMTP 服务器示例:

using System.Web.Mail;
using System;

public class MailSender
{
    public static bool SendEmail(string pGmailEmail, string pGmailPassword, string pTo, string pSubject, string pBody, MailFormat pFormat)
    {
        try
        {
            MailMessage myMail = new MailMessage();
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");

            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", pGmailEmail);
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", pGmailPassword);
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");

            myMail.From = pGmailEmail;
            myMail.To = pTo;
            myMail.Subject = pSubject;
            myMail.BodyFormat = pFormat;
            myMail.Body = pBody;

            SmtpMail.SmtpServer = "smtp.gmail.com:465";
            SmtpMail.Send(myMail);

            return true;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

以上是如何使用 .NET Framework 配置 SSL SMTP 电子邮件发送?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn