.NET and C#-tips

Forums

Topic ".NET och C#-tips".
General guides, tips and tricks..

Comments

Permalink

Testing C# using .NET Fiddle: 
https://dotnetfiddle.net/  

Link to Repl.it example using "Linq": 
https://replit.com/@NisseBengtsson/linq-sample-1#main.cs

Link to Repl.it example that will send a mail using SMTP: 
https://replit.com/@NisseBengtsson/smtp-test
 (Code works from Replit when "app password" has been set, but dotnetfiddle does not allow SMTP.)
  

Below is the code copied from "Replit" just in case it might "get lost"..
using System;
using System.Net;
using System.Net.Mail;
using System.Text;

public class Program
{
  public static void Main()
  {
    // Example to send email using SMTP.
    // Using Gmail requires that you configure an "app password"..
    //  (since you otherwise will need 2-factor authentication))
    // This password is probably in the form of a string like "aaaa bbbb cccc dddd eeee".

    // fromAddress, fromName, code
    MailAddress from = new MailAddress("sender@gmail.com", "Someone", Encoding.UTF8);
    MailAddress to = new MailAddress("benzzon@gmail.com"); // toAddress
    MailMessage message = new MailMessage(from, to);
    message.Subject = "This is a test-mail";
    message.SubjectEncoding = Encoding.UTF8;
    string dateTime = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss");
    message.Body = $"This is just a test-mail sent from replit.com.. ({dateTime})";
    message.BodyEncoding = Encoding.UTF8;

    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
    // IMPORTANT: Password needs to be set on the line below!
    smtp.Credentials = new NetworkCredential("benzzon@gmail.com", "PASSWORD");
    smtp.EnableSsl = true;

    try
    {
      smtp.Send(message);
      smtp.Dispose();
      message.Dispose();
      Console.WriteLine("Mail was sent.");
    }
    catch(Exception ex)
    {
      Console.WriteLine("Exception occurred.. " + ex.Message);
    }
  }
}