Introduction
In my previous article I explained
Send Email Using ASP.Net With C#. In this article I will explain how to send multiple emails with attachments. If you don't bother about the code because I just change some codes in my previous article. ! Let's start.
Code
- protected void btn_sendemail_Click(object sender, EventArgs e)
- {
-
- string to = Txt_toaddress.Text;
- string from = "fromaddress";
- string[] Multiple = to.Split(',');
- MailMessage message = new MailMessage();
- message.From = new MailAddress(from);
-
- foreach (string multiple_email in Multiple)
- {
- message.To.Add(new MailAddress(multiple_email));
- }
- if (FileUpload2.HasFile)
- {
- string FileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
- message.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileName));
-
- }
-
- string mailbody = Txt_Bodycontent.Text;
- message.Subject = Txt_Subject.Text;
- message.Body = mailbody;
- message.BodyEncoding = Encoding.UTF8;
- message.IsBodyHtml = true;
- SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
- System.Net.NetworkCredential basicCredential1 = new
- System.Net.NetworkCredential("fromaddress", "fromaddresspassword");
- client.EnableSsl = true;
- client.UseDefaultCredentials = false;
- client.Credentials = basicCredential1;
- try
- {
- client.Send(message);
- }
-
- catch (Exception ex)
- {
- throw ex;
- }
- }
We must add the following namespace:
- using System.Net;
- using System.Net.Mail;
- using System.Text;
Multiple Email
The following code will help to split the Comma
'"," Separated email in the given textbox( Txt_toaddress.Text ).
- string to = Txt_toaddress.Text;
- string from = "fromaddress";
- string[] Multiple = to.Split(',');
- MailMessage message = new MailMessage();
- message.From = new MailAddress(from);
-
- foreach (string multiple_email in Multiple)
- {
- message.To.Add(new MailAddress(multiple_email));
- }
Attachment
If you want to send an attachment with email you can add the following code. Otherwise you just remove this part in the code.
- if (FileUpload2.HasFile)
- {
- string FileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
- message.Attachments.Add(new Attachment(FileUpload2.PostedFile.InputStream, FileName));
-
- }
File Upload
If you want to select multiple files in a single file uploader, then you just add
AllowMultiple="true". This is one of the option in ASP file upload.
- <div>
- <asp:FileUpload runat="server" ID="FileUpload2" AllowMultiple="true" />
- </div>
Design
Output
Common Error for sending an Email
Check the following reference to solve your 5.5.1 Authentication.
Reference: You can also see this in my blog:
Summary
We learned how to send multiple emails with attachment using ASP.NET and C#. I hope this article is useful for all .NET beginners.