尝试用 C# 发送邮件,但似乎不起作用

本文关键字:不起作用 | 更新日期: 2023-09-27 18:31:00

所以我想尝试使用 Visual C# 应用程序向自己发送一些邮件,但它似乎只是运行代码(我知道这一点,因为我在代码末尾放了一个消息框)并且不发送任何内容。出于显而易见的原因,我确实更改了下面的电子邮件信息。

这是我所拥有的:

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;
using System.Net;
namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
    private void button1_Click(object sender, EventArgs e)
    {
        string Host = "smtp.live.com";
        Int16 Port = 587;
        bool SSL = true;
        string Username = "myemail@hotmail.com";
        string Password = "mypassword";
        // Mail options
        string To = "myemail@hotmail.com";
        string From = "email@hotmail.com";
        string Subject = "This is a test";
        string Body = "It works!";
        MailMessage mm = new MailMessage(From, To, Subject, Body);
        SmtpClient sc = new SmtpClient(Host, Port);
        NetworkCredential netCred = new NetworkCredential(Username, Password);
        sc.EnableSsl = SSL;
        sc.UseDefaultCredentials = false;
        sc.Credentials = netCred;
        MessageBox.Show("Test");
    }
}
}

*注意,我没有收到任何错误。

尝试用 C# 发送邮件,但似乎不起作用

您实际上并没有发送邮件。

将其添加到您的代码中 - 您应该能够找出以下位置:

sc.Credentials = netCred;
try 
{
  sc.Send(message);
}  
catch (Exception ex) 
{
  MessageBox(ex.ToString());              
}              
MessageBox.Show("Test");

添加这些命名空间...

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

在要发送电子邮件的代码隐藏文件中添加以下代码行。

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage("yourEmailId", "destinationEmailId");
mail.Subject = ""; //Enter the text for the subject of the mail in quotes.
mail.Body = ""; //Enter the text for the body of mail within the quotes.
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.live.com");
NetworkCredential cred = new NetworkCredential("yourEmailId", "yourPassword");
client.EnableSsl = true;
client.Credentials = cred;
try
{
client.Send(mail);
}
catch (Exception)
{
}