send outlook emails in C# code example
Example 1: sending email using c#
using System;
using System.Windows.Forms;
using System.Net.Mail;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("[email protected]");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
Example 2: c# send email with attachment
using System.Net;
using System.Net.Mail;
...
using (SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"))
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail - 1";
mail.Body = "Mail with attachment";
mail.IsBodyHtml = false;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("C:/Users/picture.jpg");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("[email protected]", "emailpassword1234");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
}