从app.config发送邮件和提取数据

时间:2013-08-07 19:06:46

标签: c# asp.net

我有一个情况。 HTML代码是标准的,有三个文本框和一个按钮:

<add key="cma_contact_form_email" value="somec@gmail.com"/>
<add key="cma_contact_to_address" value="some@gmail.com"/>
<add key="smtpServer" value="smtp.gmail.com" />
<add key="EnableSsl" value = "true"/>
<add key="smtpPort" value="993" />
<add key="smtpUser" value="some@gmail.com" />
<add key="smtpPass" value="pass" />

代码背后:

protected void ImageButton_Click(Object sender, EventArgs e){
        MailMessage msg = new MailMessage();
        msg.To.Add(ConfigurationManager.AppSettings["cma_contact_form_email"]);
        msg.From = new        MailAddress(ConfigurationManager.AppSettings["cma_contact_to_address"]);

        msg.Body += "Name: " + txtName.Text + "\n";
        msg.Body += "Email: " + txtEmail.Text + "\n";
        msg.Body += "Message: \n" + txtMessage.Text + "\n";
        msg.Subject = txtName.Text;

        msg.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = ConfigurationManager.AppSettings["smtpServer"]; //Or Your SMTP Server Address
        smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["smtpPort"]);

        smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
        smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["smtpUser"], ConfigurationManager.AppSettings["smtpPass"]);
        //Or your Smtp Email ID and Password
        try
        {
            smtp.Send(msg);
            lblPost.Text = "Thank you, your question has been submitted to our CMA heldesk.";
        }
        catch (Exception ex)
        {

            lblPost.Text = "Error occured while sending your message. "  + ex.Message;
        }

        placeholder.Visible = false;
        msgplaceholder.Visible = true;
    }

通常情况下这应该有效,但是我收到了超时错误。谁知道捕获的位置?谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用以下方法检查在实际发送到电子邮件之前是否允许连接,并且还应该处理 SmtpException 。它有一个 StatusCode 属性,它会告诉你Send()失败的原因。

您可以像这样调用以下方法

if(TestConnection("smtpServerAddress",port))
  SendEmail();

public static bool TestConnection(string smtpServerAddress, int port)
    {
        IPHostEntry hostEntry = Dns.GetHostEntry(smtpServerAddress);
        IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port);
        using (Socket tcpSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
        {
            //try to connect and test the rsponse for code 220 = success
            tcpSocket.Connect(endPoint);
            if (!CheckResponse(tcpSocket, 220))
            {
                return false;
            }

            // send HELO and test the response for code 250 = proper response
            SendData(tcpSocket, string.Format("HELO {0}\r\n", Dns.GetHostName()));
            if (!CheckResponse(tcpSocket, 250))
            {
                return false;
            }

            // if we got here it's that we can connect to the smtp server
            return true;
        }
    }

  private static bool CheckResponse(Socket socket, int expectedCode)
{
    while (socket.Available == 0)
    {
        System.Threading.Thread.Sleep(100);
    }
    byte[] responseArray = new byte[1024];
    socket.Receive(responseArray, 0, socket.Available, SocketFlags.None);
    string responseData = Encoding.ASCII.GetString(responseArray);
    int responseCode = Convert.ToInt32(responseData.Substring(0, 3));
    if (responseCode == expectedCode)
    {
        return true;
    }
    return false;
}

GMAIL设置

  • Gmail SMTP服务器地址:smtp.gmail.com
  • Gmail SMTP用户名:example@gmail.com
  • Gmail SMTP密码:密码
  • Gmail SMTP端口:465
  • 需要Gmail SMTP TLS / SSL:是

答案 1 :(得分:1)

问题:您在设置中提到的端口适用于IMAP,

解决方案 GMAIL SMTP 的正确端口为port 465,而不是port 993IMAP