2012-06-07 4 views
0

원격/격리 된 컴퓨터에서 실행되는 Windows 양식 응용 프로그램을 만들고 관리자에게 전자 메일로 오류 알림을 보냅니다. 나는 이것을 달성하기 위해 System.Net.Mail 클래스를 사용하려고했지만 나는 이상한 문제로 실행 해요 :Windows 양식 응용 프로그램에서 전자 메일 보내기

System.IO.IOException: Unable to read data from the transport connection: 
An existing connection was forcibly closed by the remote host.---> 
System.Net.Sockets.SocketException: An existing connection was forcibly closed by 
the remote host at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, 
Int32 size, SocketFlags socketFlags) at System.Net.Sockets.NetworkStream. 
Read(Byte[] buffer, Int32 offset, Int32 size) 

2 내가 네트워크 스니핑 시도 :

1 내가 오류 메시지가 활동이 잘못되었는지 확인하십시오. 이 시점에서

i) The DNS lookup for my SMTP server's hostname works 
ii) My application connects to the SMTP server and sends "EHLO MY-HOSTNAME" 
iii) SMTP server responds back with it's usual 
iv) My application sends "AUTH login abcdxyz" and receives an acknowledgement packet 

SMTP 서버가 암호를 요구하지 않는 것 중 하나 보인다 또는 내 컴퓨터를 요청할 수있는 SMTP 서버 전에 SMTP 서버로의 연결을 차단 : 그래서 여기가는 방법 암호.

다른 SMTP 포트와 SMTP 호스트를 사용해 보았습니다. 또한 방화벽과 AV를 사용하지 못하게했지만 운이 없었습니다. PuTTY를 사용하여 SMTP 서버에 연결하고 내 응용 프로그램과 동일한 명령 시퀀스를 실행하는 동안 (패킷 스니퍼에서 가져옴) 모든 것이 정상적으로 작동하고 전자 메일을 보낼 수 있습니다.

Imports System.Net 
Imports System.Net.Mail 

Public Function SendMail() As Boolean 

    Dim smtpClient As New SmtpClient("smtp.myserver.com", 587) 'I tried using different hosts and ports 
    smtpClient.UseDefaultCredentials = False 
    smtpClient.Credentials = New NetworkCredential("[email protected]", "password") 
    smtpClient.EnableSsl = True 'Also tried setting this to false 

    Dim mm As New MailMessage 
    mm.From = New MailAddress("[email protected]") 
    mm.Subject = "Test Mail" 
    mm.IsBodyHtml = True 
    mm.Body = "<h1>This is a test email</h1>" 
    mm.To.Add("[email protected]") 

    Try 
      smtpClient.Send(mm) 
      MsgBox("SUCCESS!") 
    Catch ex As Exception 
      MsgBox(ex.InnerException.ToString) 
    End Try 

    mm.Dispose() 
    smtpClient.Dispose() 

    Return True 

End Function 

어떤 조언 :

여기에 내가 사용하고 코드인가?

+2

우리는 코드를 볼 수 있을까요? –

+0

내 게시물에 코드를 추가했습니다 ... – Zishan

+0

이 코드를 사용하고 gmail 계정 자격 증명을 사용하는 경우 예를 들어 같은 오류가 발생합니까? Diogo 언급처럼 ... –

답변

4

는 다음과 같이 작동 :

public SmtpClient client = new SmtpClient(); 
    public MailMessage msg = new MailMessage(); 
    public System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential("mail", "password"); 

    public void Send(string sendTo, string sendFrom, string subject, string body) 
    { 
     try 
     { 
      //setup SMTP Host Here 
      client.Host = "smtp.gmail.com"; 
      client.Port = 587; 
      client.UseDefaultCredentials = false; 
      client.Credentials = smtpCreds; 
      client.EnableSsl = true; 

      //converte string to MailAdress 

      MailAddress to = new MailAddress(sendTo); 
      MailAddress from = new MailAddress(sendFrom); 

      //set up message settings 

      msg.Subject = subject; 
      msg.Body = body; 
      msg.From = from; 
      msg.To.Add(to); 

      // Enviar E-mail 

      client.Send(msg); 

     } 
     catch (Exception error) 
     { 
      MessageBox.Show("Unexpected Error: " + error); 
     } 
    } 

전화하는 것을 잊지 말아

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    private void btnTest_Click(object sender, RoutedEventArgs e) 
    { 
     MailAddress from = new MailAddress("[email protected]", "Name and stuff"); 
     MailAddress to = new MailAddress("[email protected]", "Name and stuff"); 
     List<MailAddress> cc = new List<MailAddress>(); 
     cc.Add(new MailAddress("[email protected]", "Name and stuff")); 
     SendEmail("Want to test this damn thing", from, to, cc); 
    } 

    protected void SendEmail(string _subject, MailAddress _from, MailAddress _to, List<MailAddress> _cc, List<MailAddress> _bcc = null) 
    { 
     string Text = ""; 
     SmtpClient mailClient = new SmtpClient("Mailhost"); 
     MailMessage msgMail; 
     Text = "Stuff"; 
     msgMail = new MailMessage(); 
     msgMail.From = _from; 
     msgMail.To.Add(_to); 
     foreach (MailAddress addr in _cc) 
     { 
      msgMail.CC.Add(addr); 
     } 
     if (_bcc != null) 
     { 
      foreach (MailAddress addr in _bcc) 
      { 
       msgMail.Bcc.Add(addr); 
      } 
     } 
     msgMail.Subject = _subject; 
     msgMail.Body = Text; 
     msgMail.IsBodyHtml = true; 
     mailClient.Send(msgMail); 
     msgMail.Dispose(); 
    } 
} 

using System.Net.Mail;

잊지 마세요

I 얇음 그것은 여기에 다음과 같이 작동 코드입니다 VB에서 k는, 내가 자주 vb.net에 기록하지 않는, 약간의 오차가있을 수 있습니다 :

Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) 
    Dim _from As New MailAddress("[email protected]", "Name and stuff") 
    Dim _to As New MailAddress("[email protected]", "Name and stuff") 
    Dim cc As New List(Of MailAddress) 
    cc.Add(New MailAddress("[email protected]", "Name and stuff")) 
    SendEmail("Wan't to test this fucking thing", _from, _to, cc) 
End Sub 

Protected Sub SendEmail(ByVal _subject As String, ByVal _from As MailAddress, ByVal _to As MailAddress, ByVal _cc As List(Of MailAddress), Optional ByVal _bcc As List(Of MailAddress) = Nothing) 

    Dim Text As String = "" 
    Dim mailClient As New SmtpClient("Mailhost") 
    Dim msgMail As MailMessage 
    Text = "Stuff" 
    msgMail = New MailMessage() 
    msgMail.From = _from 
    msgMail.To.Add(_to) 
    For Each addr As MailAddress In _cc 
     msgMail.CC.Add(addr) 
    Next 
    If _bcc IsNot Nothing Then 
     For Each addr As MailAddress In _bcc 
      msgMail.Bcc.Add(addr) 
     Next 
    End If 
    msgMail.Subject = _subject 
    msgMail.Body = Text 
    msgMail.IsBodyHtml = True 
    mailClient.Send(msgMail) 
    msgMail.Dispose() 
End Sub 

가져 잊지 마세요 System.Net.Mail

+0

감사합니다 Thanatos,하지만 내 코드 또는 Diogo 게시 한 것과 많이 다르지 않습니다. 이 문제는 Visual Studio가 내가 사용하는 케이블 연결 (동일한 케이블 연결과 다른 SMTP 또는 텔넷 클라이언트를 사용하는 SMTP 포트에 연결하는 데 문제가 없음)을 통해 SMTP 서버에 연결할 때 SMTP 서버가 연결을 닫는 것으로 보입니다. 그러나 다른 연결을 사용하여 연결하면 (제 2의 보조 컴퓨터가 3G 임) Visual Studio에 문제가없는 것 같습니다. – Zishan

+0

SendAsync 메서드를 사용해 보셨습니까? Timeout이 원인 일 때 작동 할 수도 있습니다. [link] (http://msdn.microsoft.com/en-us/library/x5x13z6h#Y0) 이것은 당신을 도울 MSDN 사이트입니다. @ 지산 – Tartori

0

시도는이를 사용 : C#에서

using System.Net.Mail; 
using System.Windows.Forms; 
+0

Diogo에게 감사 드려요.하지만이 코드는 방금 위에 게시 한 코드와 같습니다. System.Windows.Forms에 대한 호출이 필요 없습니다. – Zishan

+0

이것은 나에게 잘 작동하고, 당신이 올바르게 smtp configs 있는지보십시오. – Severiano

4
SendMail.CS Page 

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net; 
using System.Net.Mail; 

namespace SendMailUsingWindowsForms 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      try 
      { 

       //Sending the email. 
       //Now we must create a new Smtp client to send our email. 

       SmtpClient client = new SmtpClient("smtp.gmail.com", 25); //smtp.gmail.com // For Gmail 
                      //smtp.live.com // Windows live/Hotmail 
                      //smtp.mail.yahoo.com // Yahoo 
                      //smtp.aim.com // AIM 
                      //my.inbox.com // Inbox 


       //Authentication. 
       //This is where the valid email account comes into play. You must have a valid email account(with password) to give our program a place to send the mail from. 

       NetworkCredential cred = new NetworkCredential("*******@gmail.com", "........"); 

       //To send an email we must first create a new mailMessage(an email) to send. 
       MailMessage Msg = new MailMessage(); 

       // Sender e-mail address. 
       Msg.From = new MailAddress(textBox1.Text);//Nothing But Above Credentials or your credentials (*******@gmail.com) 

       // Recipient e-mail address. 
       Msg.To.Add(textBox2.Text); 

       // Assign the subject of our message. 
       Msg.Subject = textBox3.Text; 

       // Create the content(body) of our message. 
       Msg.Body = textBox4.Text; 

       // Send our account login details to the client. 
       client.Credentials = cred; 

       //Enabling SSL(Secure Sockets Layer, encyription) is reqiured by most email providers to send mail 
       client.EnableSsl = true; 

       //Confirmation After Click the Button 
       label5.Text = "Mail Sended Succesfully"; 

       // Send our email. 
       client.Send(Msg); 



      } 
      catch 
      { 
       // If Mail Doesnt Send Error Mesage Will Be Displayed 
       label5.Text = "Error"; 
      } 
     } 


    } 
} 

는 SendMail.Design enter image description here

enter image description here

관련 문제