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

时间:2016-09-12 18:22:19

标签: c# sql asp.net mailmessage

我有以下电子邮件功能,可以向用户列表发送电子邮件。我使用方法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并从表中获取用户列表,而不是从此函数获取?谢谢您的帮助!

3 个答案:

答案 0 :(得分:4)

  

我以最简单的方式想出了自己。我希望这可以帮助别人。感谢所有回复积极评论的人,有能力思考并运用常识。

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();
    }
}

答案 1 :(得分:1)

您可以在当前项目中创建此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);
        }
    }
}

//如果要传递List并连接到.Split函数中使用的单个管道分隔字符串字符串,则可以更改方法签名以获取字符串并将其传递给电子邮件,例如< / p>

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

答案 2 :(得分:0)

您可以做很多事情来优化和概括下面的代码 - 它尽可能地接近您的代码,同时做您想做的事情。由您来决定如何连接到您的数据库并获取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