我只是尝试制作一个c#控制台程序。我们的想法是创建一个小的自包含应用程序,它将检查数据库并通过电子邮件将列表发送给一堆用户,例如每天早上它会自动运行。
我还没有到目前为止,只是试着先把基础知识降下来。通过在线查看教程,我已经能够连接到数据库并在控制台中显示列表。然而,发送邮件不太成功。
如果我在while循环中包含用于发送邮件的代码,它将生成一堆单独的邮件,因此出于某种原因可行。但这不是我想要的。我希望列表运行并编译一个将成为消息体的列表。程序的那部分运行后,我想发送邮件。问题是它不起作用,当我查看服务器日志时,一个SMTP会话被打开但它终止并说套接字错误发送响应到DATA 下一行说 Winsock错误10045 并且会话终止。
知道为什么会这样吗?对我来说真正没有意义的是,如果在while循环中运行它会起作用...
这是目前的整个计划:
namespace SendMails
{
class ConnectToMySQL
{
[STAThread]
static void Main(string[] args)
{
string connStr = createConnstr("192.168.111.1","database","login","passwd");
MySqlConnection conn = null;
MySqlDataReader reader = null;
try
{
conn = new MySqlConnection(connStr);
conn.Open();
string stm = "SELECT id, name, surname FROM Kat WHERE Contact = 'Yes' AND Contactwhen <= '"+ DateTime.Today + "'";
MySqlCommand cmd = new MySqlCommand(stm, conn);
reader = cmd.ExecuteReader();
//The actual output on the screen.
while (reader.Read())
{
Console.WriteLine(reader.GetInt32(0) + ": " + reader.GetString(1) + " " + reader.GetString(2));
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
}
finally
{
if (conn != null)
{
conn.Close();
}
}
createMail("me@company.com", "info@company.com", "Test message", "Here is your test message.");
}
//This builds a mysql connection string
public static string createConnstr(string server, string databaseName, string user, string passw)
{
//build connection string
string connStr = "server=" + server + ";database=" + databaseName + ";uid=" + user + ";password=" + passw + ";";
//return connection string
return connStr;
}
//This sends an email
static void createMail(string recipient, string from, string subject, string msg)
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(recipient);
message.Subject = subject;
message.From = new System.Net.Mail.MailAddress(from);
message.Body = msg;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("192.168.111.1");
try
{
Console.WriteLine("Sending mail...");
smtp.Send(message);
Console.WriteLine("Mail was sent successfully!");
}
catch (Exception ep)
{
Console.WriteLine("failed to send mail:");
Console.WriteLine(ep.Message);
}
}
}
}
答案 0 :(得分:0)
问题现在解决了。解决方案很尴尬。
仅需要在 smtp.Send(消息);
行之后添加 smtp.Dispose();