欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

.NET邮件发送 SMTP邮件发送 - ???? 使用QQ邮箱发送邮件

最编程 2024-04-21 21:24:20
...

首先需要设置开启邮箱的SMTP服务

登录(https://mail.qq.com/)电脑网页版邮箱进入【设置】->【帐户】->【POP3/IMAP/SMTP服务】, 开启或关闭相应服务最后保存更改即可。

QQ邮箱 POP3 和 SMTP 服务器地址设置如下:

邮箱 POP3服务器(端口995) SMTP服务器(端口465或587)
qq.com pop.qq.com smtp.qq.com

SMTP服务器需要身份验证。

以下是示例代码:

using ConsoleApp1Test;
//xxx
string server = "smtp.qq.com";
string username = "my test email";
string password = "xxx;
string from = "from@qq.com";
string to =   "to@qq.com";
string subject = "Test Email";
string content = "This is a test email sent asynchronously.";
bool isHtml = false; // 是否为 HTML 格式

try
{
    bool success = await MailHelper. SendMailAsync(server, username, password, from, to, null, subject, content, isHtml);
    if (success)
    {
        Console.WriteLine("邮件发送成功!");
    }
    else
    {
        Console.WriteLine("邮件发送失败!");
    }
}
catch (Exception ex)
{
    Console.WriteLine($"邮件发送出错:{ex.Message}");
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1Test
{
    internal class MailHelper
    {

    

      public static async Task<bool> SendMailAsync(string server, string username, string password, string from, string to, string cc, string subject, string content, bool isHtml)
    {
        try
        {
            using (var smtp = new SmtpClient(server))
            {
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential(username, password);
                smtp.EnableSsl = true; // 启用加密
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

                using (var mail = new MailMessage())
                {
                    mail.From = new MailAddress(from);
                    mail.To.Add(to);
                    mail.SubjectEncoding = Encoding.UTF8;
                    mail.Subject = subject;
                    mail.IsBodyHtml = isHtml;
                    mail.BodyEncoding = Encoding.UTF8;
                    mail.Body = content;

                    await smtp.SendMailAsync(mail); // 异步发送邮件
                }

                return true;
            }
        }
        catch (Exception err)
        {
            // 发送失败时的异常处理
            // 可以在此处记录日志
            return false;
        }
    }

}
}