Send Email by using .Net via SMTP-Server

Tags: smtp

Sometimes it’s easier to send an Email without using the Outlook Object Modell.
The .Net Framework already has the capability to send emails using a SMTP-Server.
This snippet sends an Email using a specific SMTP-Host and uses basic authentication:

void SendMail(string from, string to, string subject, string message){

    MailMessage mailMessage = new MailMessage(from, to);
    mailMessage.Subject = subject;
    mailMessage.Body = message;

    SmtpClient smtpClient = new SmtpClient();
    smtpClient.Host = "";
    smtpClient.Port = 25;

    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = new NetworkCredential("username", "password");
    try {
        MessageBox.Show("The Message has been sent.");
    } catch (Exception ex) {
        MessageBox.Show(string.Format("There was an Error while sending the message:;\n{0}", ex.Message));

Happy coding!


Add a Comment