试图用C#发送邮件,但似乎没有用

时间:2012-04-14 02:29:54

标签: c# email smtp

所以我想尝试使用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");
    }
}
}

*注意,我从中得不到任何错误。

2 个答案:

答案 0 :(得分:2)

您实际上并未发送邮件。

将此添加到您的代码中 - 您应该能够找出:

sc.Credentials = netCred;

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

答案 1 :(得分:-1)

添加这些命名空间......

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

在要发送电子邮件的Code-Behind文件中添加以下代码行。

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