我刚刚尝试制作 ac# 控制台程序。这个想法是制作一个小型的自包含应用程序,它将检查数据库并通过电子邮件将列表发送给一群用户,例如每天早上自动运行。
到目前为止,我还没有做到这一点,只是想先了解一下基础知识。通过查看在线教程,我已经能够连接到数据库并在控制台中显示一个列表。然而,发送邮件不太成功。
如果我在 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);
}
}
}
}