我目前的程序有問題,我正在嘗試學習如何使用smtp發送電子郵件,並且我編寫了此代碼來執行此操作。當我嘗試點擊button1時,程序凍結而沒有任何反應。 PS:很明顯,在發佈之前,我已將電子郵件和密碼更改爲「電子郵件」和「密碼」。 PS2:我正在用葡萄牙語寫我的代碼,所以你可能不明白的任何東西只是作爲變量或「x」來考慮。試圖用smtp發送電子郵件時程序凍結
編輯:我用一個簡單的線解決了這個問題,程序中缺少一個端口,誰有同樣的問題只需添加smtp.Port = 587; 。下面
代碼:
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();
}
}
}
哦......看來,我有工作要做。 –