In the previous article, we have seen how to send Email using SMTP in C#. In this article, let us see how to send an email with attachment using SMTP protocol in C#.
This example uses Gmail SMPT server for sending a mail with attachment in C#. The below code snippet shows how to add an attachment to the mail object.
This example uses Gmail SMPT server for sending a mail with attachment in C#. The below code snippet shows how to add an attachment to the mail object.
System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment("your attachment file"); mail.Attachments.Add(attachment);
The Complete Source Code for sending an attachment in 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("your_email_address@gmail.com"); mail.To.Add("to_address"); mail.Subject = "Test Mail - 1"; mail.Body = "mail with attachment"; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment("your attachment file"); mail.Attachments.Add(attachment); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password"); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); MessageBox.Show("mail Send"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } }