在C#3.5中发送电子邮件失败

时间:2010-12-17 09:04:33

标签: c# .net

发送电子邮件时,我收到以下错误:

  

在System.Net.Mail.SmtpClient.Send(MailMessage消息)中设备尚未就绪。

代码是:

MailMessage mailMessage = new MailMessage(senderEmail, cleanRecipients)
{
    Subject = string.empty,
    Body = string.empty,
    IsBodyHtml = false
};
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);

2 个答案:

答案 0 :(得分:7)

要发送电子邮件,您需要SMTP服务器,因此请确保在配置文件中指定了SMTP服务器。

<system.net>
    <mailSettings>
      <smtp from="someaddress@mydomain.com">
        <network host="mail.mydomain.com" password="secret" port="25" userName="someaddress@mydomain.com" />
      </smtp>
    </mailSettings>
</system.net>

答案 1 :(得分:3)

这段代码可能会有所帮助!

string from = me@gmail.com; //Replace this with your own correct Gmail Address

string to = you@gmail.com //Replace this with the Email Address to whom you want to send the mail

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
 mail.To.Add(to);
 mail.From = new MailAddress(from, "One Ghost" , System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail" ;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true ;
mail.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password

 client.Credentials = new System.Net.NetworkCredential(from, "Password");

client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
       try
        {
            client.Send(mail);
        }
        catch (Exception ex) 
        {
            Exception ex2 = ex;
            string errorMessage = string.Empty; 
            while (ex2 != null)
            {
                errorMessage += ex2.ToString();
                ex2 = ex2.InnerException;
            }
   HttpContext.Current.Response.Write(errorMessage );
        } // end try