使用 System.Net.Mail 从用户的数据库列表发送电子邮件

Using System.Net.Mail to send email from Database list of user

我有以下电子邮件功能,可以向用户列表发送电子邮件。我使用 message.To.Add(new MailAddress("UserList@email.com")):

方法添加用户
Using System.Net.Mail

protected void SendMail()
{     

    //Mail notification
    MailMessage message = new MailMessage();
    message.To.Add(new MailAddress("UserList@email.com"));
    message.Subject = "Email Subject ";
    message.Body = "Email Message";
    message.From = new MailAddress("MyEmail@mail.com");

    // Email Address from where you send the mail
    var fromAddress = "MyEmail@mail.com";

    //Password of your mail address
    const string fromPassword = "password";

    // smtp settings
    var smtp = new System.Net.Mail.SmtpClient();
    {
        smtp.Host = "smtp.mail.com";
        smtp.EnableSsl = true;
        smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
        smtp.Timeout = 20000;
    }
    // Passing values to smtp object        
    smtp.Send(message);
}

但是,我怎样才能连接到 SQL-Server Db 并从 table 中获取用户列表,而不是从这个函数中获取?谢谢您的帮助!

您可以做很多事情来优化和概括下面的代码 - 它在执行您想要的操作时尽可能接近您的代码。由您决定如何连接到您的数据库并获取 DataReader.Read()。试试——如果你遇到困难,请问一些具体的问题。

Using System.Net.Mail

protected void SendMail()
{     
Dictionary<string,string> recipients = new Dictionary<string,string>
//--select FirstName, Email form MyClients
//while reader.Read(){
  recipients.Add(Convert.ToString(reader[0]),Convert.ToString(reader[1]));//adds from user to dictionary
//}


//Mail notification


foreach(KeyValuePair<string,string> kvp in recipients){
    MailMessage message = new MailMessage();
    message.To.Add(new MailAddress(kvp.Value));


    message.Subject = "Hello,  "+kvp.Key;
    message.Body = "Email Message";
    message.From = new MailAddress("MyEmail@mail.com");

    // Email Address from where you send the mail
    var fromAddress = "MyEmail@mail.com";

    //Password of your mail address
    const string fromPassword = "password";

    // smtp settings
    var smtp = new System.Net.Mail.SmtpClient();
    {
        smtp.Host = "smtp.mail.com";
        smtp.EnableSsl = true;
        smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
        smtp.Timeout = 20000;
    }
    // Passing values to smtp object        
    smtp.Send(message);
  }
} //This bracket was outside the code box

您可以在当前项目中创建此 utilities.cs 文件并粘贴以下代码,看看它是否更容易阅读

public class utilities
{  

    public static string ConnectionString
    {
        get { return ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString; } //change dbconn to whatever your key is in the config file
    } 

    public static string EmailRecips
    {
        get
        {
            return ConfigurationManager.AppSettings["EmailRecips"];//in the config file it would look like this <add key="EmailRecips" value="personA@SomeEmail.com|PersonB@SomeEmail.com|Person3@SomeEmail.com"/>
        }
    }   

    public static string EmailHost //add and entry in the config file for EmailHost 
    {
        get
        {
            return ConfigurationManager.AppSettings["EmailHost"];
        }
    }

    public static void SendEmail(string subject, string body) //add a third param if you want to pass List<T> of Email Address then use `.Join()` method to join the List<T> with a `emailaddr + | emailAddr` etc.. the Join will append the `|` for you if tell look up how to use List<T>.Join() Method
    {
        using (var client = new SmtpClient(utilities.EmailHost, 25)) 
        using (var message = new MailMessage()
        {
            From = new MailAddress(utilities.FromEmail),
            Subject = subject,
            Body = body
        })
        {
            //client.EnableSsl = true; //uncomment if you really use SSL
            //client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            //client.Credentials = new NetworkCredential(fromAddress, fromPassword);    

            foreach (var address in utilities.EmailRecips.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
                message.To.Add(address);
            client.Send(message);
        }
    }
}

//如果你想传递一个列表并加入一个管道分隔字符串中以在 .Split 函数中使用,那么你可以更改方法签名以获取一个字符串并将其传递给电子邮件示例

var emailList = string.Join("|", YourList<T>);

//那么新的电子邮件函数签名将如下所示

public static void SendEmail(string subject, string body, string emailList)

//然后你会用这个

替换 .Split 方法
foreach (var address in emailList.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))

I figured it out myself in the most simple way. I hope this help someone else. Thanks to everybody who responded with positive comments, have the ability to think, and use common sense.

Using System.Net.Mail

protected void SendMail()
{     

    //Mail notification
    MailMessage message = new MailMessage();
    message.Subject = "Email Subject ";
    message.Body = "Email Message";
    message.From = new MailAddress("MyEmail@mail.com");

    // Email Address from where you send the mail
    var fromAddress = "MyEmail@mail.com";

    //Password of your mail address
    const string fromPassword = "password";

    // smtp settings
    var smtp = new System.Net.Mail.SmtpClient();
    {
    smtp.Host = "smtp.mail.com";
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
    smtp.Timeout = 20000;
    }
    SqlCommand cmd = null;
    string connectionString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
    string queryString = @"SELECT EMAIL_ADDRESS FROM EMAIL WHERE EMAIL_ADDRESS = EMAIL_ADDRESS";

    using (SqlConnection connection =
               new SqlConnection(connectionString))
    {
        SqlCommand command =
            new SqlCommand(queryString, connection);
        connection.Open();
        cmd = new SqlCommand(queryString);
        cmd.Connection = connection;

        SqlDataReader reader = cmd.ExecuteReader();

        // Call Read before accessing data.
        while (reader.Read())
        {

            var to = new MailAddress(reader["EMAIL_ADDRESS"].ToString());
            message.To.Add(to);

        }

        // Passing values to smtp object        
        smtp.Send(message);

        // Call Close when done reading.
        reader.Close();
    }
}