使用SMTP发送邮件时出错 [英] Error in sending mail using SMTP

查看:143
本文介绍了使用SMTP发送邮件时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码发送邮件,但会引发错误

"SMTP服务器需要安全连接或未通过身份验证的客户端.服务器响应为:5.7.0必须首先发出STARTTLS命令.s1sm2963114iba.7"

I use following code for sending mail but it throws error

"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. s1sm2963114iba.7"

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

namespace email
{
    public partial class Form1 : Form
    {
// creating the objects of smtpclient class and mailmessage class

//smtpclient class is used to setup a smtp server client i am using gmail.

        SmtpClient client = new SmtpClient();
        MailMessage msg = new MailMessage();
        System.Net.NetworkCredential credentials = new 
System.Net.NetworkCredential("your_email@gmail.com", "Your Password");
     
  public Form1()
        {
            InitializeComponent();
        }
// we create a method name sendemail when we want to send email we just pass arguments 

        public void sendemail(string sendto ,string sendfrom, string subject, string body)
        {
            try
            {
// setting up smtp client, port other details

                client.Host = "smtp.gmail.com";
                client.Port = 587;
                client.UseDefaultCredentials = false;
                client.Credentials = credentials;
// you can skip this line it is for html emails if you want to send html emails then set msg.isbodyhtml = true
                msg.IsBodyHtml = true;
                // convert strings to mail address
                MailAddress to = new MailAddress(sendto);
                MailAddress from = new MailAddress(sendfrom);
                msg.Subject = subject;
                msg.Body = body;
                msg.To.Add(to);
                msg.From = from;
                client.Send(msg);
                MessageBox.Show("Email Sent");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "Error");
            }
        }
// on button click event we called sendemail method
        private void btnsendmail_Click(object sender, EventArgs e)
        {
            sendemail(txtto.Text.ToString(), "nishantbcaproject@gmail.com", txtsubject.Text.ToString(), txtbody.Text.ToString());
        }

推荐答案

看看这个技巧/窍门:
Have a look at this tip/trick: Sending an Email in C# with or without attachments: generic routine.[^]


这篇关于使用SMTP发送邮件时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆