Send Email Using outlook or Gmail
Posted by codingsense on January 23, 2009
In VB we had to write more complex codes to send a mail but .Net framework gives an easy option to email using any SMTP.
Here is a sample application that helps you to send email using Outlook and Gmail SMTP.
In this project you wil find the following keyworks let me brief you on them.
MailMessage: Creates an instance of the message that is to be sent through mail.
MailMessage mailMessage = new MailMessage();
AlternateView: If you want the message to be in a format other than plain text like Image or Rich Text or HTML or XML then we need to use this Alternate view. And the body of the message should be the same format that we specify in the alternate view.
string body = @"<b>The linked resouces </b> : <br/> <img src=""cid:DisplayImage""/>"; AlternateView Av1 = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html); mailMessage.AlternateViews.Add(Av1);and the alternate view is added to Mail Message.
Linked Resources: Linked resouces accepts the objects those are linked with the messages. For eg if you need to insert an image or any other object within the mail body then the resource has to be linked as
LinkedResource linkResource = new LinkedResource(FileName); linkResource.ContentId = "DisplayImage"; linkResource.ContentType.Name = FileName; Av1.LinkedResources.Add(linkResource);
and this resource has to be added into the alternate view.
Attachments: The files can be attached to the mail Message as follows
SMTPClient The SMTP client is responsible to send the mail Message that we created, this accepts the Host computer Name or IP Address of the computer that is used to send the mail message.
The Network Credentials have to be set to make the person reveal his identity. Enablessl is used if the SMTPClient uses the Secure Socket Layer(SSL) to encrypt the connection. The port no that is used for SMTP transactions is to be set. The send function will be used to send the mail.
SmtpClient theClient = new SmtpClient(txtHostComputer.Text.Trim()); theClient.Credentials = new System.Net.NetworkCredential(txtUsername.Text.Trim(), txtPassword.Text.Trim()); theClient.EnableSsl = true; theClient.Port = Convert.ToInt32(cmbPort.Text); theClient.Send(mailMessage);
Happy learning 🙂