2013-04-24 177 views
3

試圖通過SMTP服務器發送電子郵件,但我在smtp.Send(mail);代碼段中收到了不起眼的錯誤。通過SMTP服務器以編程方式發送電子郵件

服務器端,中繼IP地址看起來是正確的。抓我的腦袋想我失蹤的事。

MailMessage mail = new MailMessage(); 
mail.To.Add(txtEmail.Text); 

mail.From = new MailAddress("[email protected]"); 
mail.Subject = "Thank you for your submission..."; 
mail.Body = "This is where the body text goes"; 
mail.IsBodyHtml = false; 

SmtpClient smtp = new SmtpClient(); 
smtp.Host = "mailex.company.us"; 
smtp.Credentials = new System.Net.NetworkCredential 
    ("AdminName", "************"); 

smtp.EnableSsl = false; 


if (fileuploadResume.HasFile) 
{ 
    mail.Attachments.Add(new Attachment(fileuploadResume.PostedFile.InputStream, 
     fileuploadResume.FileName)); 
} 

smtp.Send(mail); 
+0

txtEmail是什麼樣的?您是否嘗試過在內部硬編碼電子郵件地址以查看它是否發送? – 2013-04-24 17:07:16

+0

我假設你已經在配置文件中設置了正確的SMTP設置? – keyboardP 2013-04-24 17:08:52

+0

您必須在代碼中指定「smtp.UseDefaultCredentials = false;」或者在web.config郵件設置中。另外,你指定什麼端口? – 2013-04-24 17:10:14

回答

2

嘗試在發送前添加。

供參考,這是我的標準郵件功能:

public void sendMail(MailMessage msg) 
{ 
    string username = "username"; //email address or domain user for exchange authentication 
    string password = "password"; //password 
    SmtpClient mClient = new SmtpClient(); 
    mClient.Host = "mailex.company.us"; 
    mClient.Credentials = new NetworkCredential(username, password); 
    mClient.DeliveryMethod = SmtpDeliveryMethod.Network; 
    mClient.Timeout = 100000; 
    mClient.Send(msg); 
} 

通常被稱爲是這樣的:

MailMessage msg = new MailMessage(); 
msg.From = new MailAddress("fromAddr"); 
msg.To.Add(anAddr); 

if (File.Exists(fullExportPath)) 
{ 
    Attachment mailAttachment = new Attachment(fullExportPath); //attach 
    msg.Attachments.Add(mailAttachment); 
    msg.Subject = "Subj"; 
    msg.IsBodyHtml = true; 
    msg.BodyEncoding = Encoding.ASCII; 
    msg.Body = "Body"; 
    sendMail(msg); 
} 
else 
{ 
    //handle missing attachments 
} 
0
  var client = new SmtpClient("smtp.gmail.com", 587); 
      Credentials = new NetworkCredential("sendermailadress", "senderpassword"), 
      EnableSsl = true 
      client.Send("sender mail adress","receiver mail adress", "subject", "body"); 
      MessageBox.Show("mail sent"); 
0

這是阿迪力的回答格式化C#:

public static class Email 
{ 
    private static string _senderEmailAddress = "sendermailadress"; 
    private static string _senderPassword = "senderpassword"; 

    public static void SendEmail(string receiverEmailAddress, string subject, string body) 
    { 
     try 
     { 
      var client = new SmtpClient("smtp.gmail.com", 587) 
      { 
       Credentials = new NetworkCredential(_senderEmailAddress, _senderPassword), 
       EnableSsl = true 
      }; 
      client.Send(_senderEmailAddress, receiverEmailAddress, subject, body); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Exception sending email." + Environment.NewLine + e); 
     } 
    } 
} 
相關問題