2010-11-30 13 views
5

可能性の重複:
Sending email through Gmail SMTP server with C#Gmail SMTPサーバーでC#でメールを送るには?

のC#で郵送し、GmailのSMTPサーバーを使用するために私たちがやるべきトリッキーなもののいずれかの種類がありますか?検索の多くの後、私はこれを行うためのいくつかの方法を見つけたので、結果として失敗の例外が発生しています。私はGmail用のTSL(TSLで動作するため)を扱わないためだと思いますが、これを行うためにC#でTSLを処理する方法はわかりません。私は本当に役立つサンプルや役に立つヘルプに感謝します。ここに私のコード:

public string SendMail(string senderMail, string receiverMail, string attachmentPath) 
{ 
    var fromMailAddress = new MailAddress(senderMail); 
    var toMailAddress = new MailAddress(receiverMail); 

    MailMessage mailMessage = new MailMessage(fromMailAddress, toMailAddress); 
    mailMessage.Subject = "My Subject"; 
    mailMessage.Body = "This is the body of this message for testing purposes"; 

    Attachment attachFile = new Attachment(attachmentPath); 
    mailMessage.Attachments.Add(attachFile); 

    SmtpClient emailClient = new SmtpClient(); 

    NetworkCredential credential = new NetworkCredential(); 
    credential.UserName = fromMailAddress.User; 
    credential.Password = "password"; 

    emailClient.Credentials = credential; 
    emailClient.Port = 587; 
    emailClient.Host = "smtp.gmail.com"; 

    //emailClient.EnableSsl = true; //Here should be for TSL, but how? 

    emailClient.Send(mailMessage); 
} 
+0

彼に聞かせてください! :P – Seva

+0

ようこそ!これは良い質問であり、正しいコードを添付しました。しかし、これまで同様の質問がありました。特別な例外が発生している可能性があります。あなたの例外の正確なメッセージを投稿すれば、人々はあなたをより良く助けることができます。 – Marijn

+0

"TSL"という言葉を3回使用しましたが、その内容はわかりません。あなたは "TLS"を意味しましたか? – Gabe

答えて

1

あなたは例外のメッセージを伝える必要があります。 はい、emailClient.EnableSsl = trueのコメントを外してください。 それでも機能しない場合は、ファイアウォールまたはルーターがポートをブロックしている可能性があります。

5

次のコードを試してください。これは私が長年使ってきた作業コードです。

// Configure mail client (may need additional 
    // code for authenticated SMTP servers). 
    SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587); 

    // Set the network credentials. 
    mailClient.Credentials = new NetworkCredential("[email protected]", "YourGmailPassword"); 

    //Enable SSL. 
    mailClient.EnableSsl = true; 

    // Create the mail message (from, to, subject, body). 
    MailMessage mailMessage = new MailMessage(); 
    mailMessage.From = new MailAddress("[email protected]"); 
    mailMessage.To.Add(to); 

    mailMessage.Subject = subject; 
    mailMessage.Body = body; 
    mailMessage.IsBodyHtml = isBodyHtml; 
    mailMessage.Priority = mailPriority; 

    // Send the mail. 
    mailClient.Send(mailMessage); 

参照:Sending Email using a Gmail Account

+0

ありがとう、完璧に動作します。私はほぼこの問題を処理するためにIISと手動SMTPをインストールしたいと思っていましたが、今はGmailを完璧に使えます。ありがとうございました。 – Sam

関連する問題