我有一个表单,允许用户向邮件列表(linq表)上的每个人发送电子邮件。我在使用正确的代码和语法链接到smtp服务器时遇到了麻烦。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Web.Security;
using System.Web.Mail;
using System.Configuration;
using System.Web.Configuration;
using System.Net.Configuration;
using System.Net.Mail;
public partial class MassEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
mailingListClassDataContext Class = new mailingListClassDataContext();
var emaillist = from emails in Class.mailinglistMembers select emails.email;
foreach (var subcriber in emaillist)
{
MailMessage objMail = new MailMessage();
objMail.From = "test@test.com";
objMail.To = subcriber;
objMail.BodyFormat = MailFormat.Html ;
//The subject of the message
objMail.Subject = "test email that i hope works" ;
//he message text
objMail.Body = Editor1.Content;
//need help in this area
SmtpClient client = new SmtpClient();
SmtpClient.Send(objMail);
}
}
}
答案 0 :(得分:4)
最佳解决方案是将smtp服务器详细信息放在web.config
中 <system.net>
<mailSettings>
<smtp>
<network
host="smtp.emailhost.com"
port="25"
userName="username"
password="password" />
</smtp>
</mailSettings>
</system.net>
<system.web>
答案 1 :(得分:1)
using (var db = new mailingListClassDataContext())
{
var client = new System.Net.Mail.SmtpClient();
var recipients = from e in db.mailinglistMembers
select e.email;
foreach (string recipient in recipients)
{
var message = new System.Net.Mail.MailMessage("sender@example.com", recipient);
message.Subject = "Hello World!";
message.Body = "<h1>Foo bar</h1>";
message.IsBodyHtml = true;
client.Send(message);
}
}
尝试在 web.config 或 machine.config 中设置配置。确保您已指定SMTP服务器的正确地址和端口。
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="network" from="me@example.com">
<network
host="localhost"
port="25"
defaultCredentials="true"
/>
</smtp>
</mailSettings>
</system.net>
</configuration>
答案 2 :(得分:0)
您可以将构造函数中的SMTP服务器IP或名称传递给SmtpClient,也可以通过Host属性将其设置为明确。
答案 3 :(得分:0)
您可能希望在SmptClient
上设置Host
(可能还有Credentials
)属性。服务器(主机)默认为localhost。
还要考虑在循环外创建client
实例。