【发布时间】:2018-02-25 16:58:43
【问题描述】:
我的程序目前遇到了一个严重问题,我正在尝试学习如何使用 smtp 发送电子邮件,我编写了这段代码来做到这一点。当我尝试单击 button1 时,程序冻结并且没有任何反应。 PS:显然,我在发布之前将电子邮件和密码更改为“电子邮件”和“密码”。 PS2:我正在用葡萄牙语编写代码,因此,您可能不理解的任何内容都可以视为变量或“x”。
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Mail;
using MySql.Data.MySqlClient;
using System.Net;
namespace Inicio
{
public partial class Email : Form
{
MySqlConnection con = new MySqlConnection(@"Data Source=localhost;port=3306;Initial Catalog=digital wallet;User ID=root;password=");
public Email()
{
InitializeComponent();
}
private void SendEmail()
{
if (textBox1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Preencha todos os campos", "Erro",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
int i = 0;
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select EMAIL from conta where EMAIL = @email and LOGIN = @login ";
cmd.Parameters.AddWithValue("@email", textBox2.Text);
cmd.Parameters.AddWithValue("@login", textBox1.Text);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
MessageBox.Show("Login ou email inválidos", "Erro",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
cmd.CommandText = "select * from CONTA where LOGIN = @login";
cmd.ExecuteNonQuery();
string senha = "";
string email = "";
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
senha = reader.GetString("SENHA");
email = reader.GetString("EMAIL");
}
reader.Close();
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "outlook.com";
smtp.UseDefaultCredentials = false;
NetworkCredential netCred = new NetworkCredential("email", "password");
smtp.Credentials = netCred;
smtp.EnableSsl = true;
using (MailMessage msg = new MailMessage("email", email))
{
msg.Subject = "Recuperação de senha.";
StringBuilder sb = new StringBuilder();
sb.AppendLine("A sua senha é atual é: " + senha + Environment.NewLine);
sb.AppendLine("Obrigado," + Environment.NewLine);
sb.AppendLine("Digital wallet. " + Environment.NewLine);
msg.Body = sb.ToString();
msg.IsBodyHtml = false;
smtp.Send(msg);
}
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
SendEmail();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
【问题讨论】:
-
如果您解决了问题,请发布答案。不要将解决方案编辑到您的问题中。
标签: c# winforms email smtp freeze