Send Mail using C# code

The sendEmail method is an example of how to programmatically send emails using C#. It demonstrates the usage of the System.Net.Mail namespace to create and send an email with an attachment. The method assumes the use of an SMTP server for sending the email.

public void sendEmail()  
{  
    String userName = "[email protected]";  
    String password = "password for from address";  
    MailMessage msg = new MailMessage("[email protected] ", " [email protected] ");  
    msg.Subject = "Your Subject Name";  
    StringBuilder sb = new StringBuilder();  
    sb.AppendLine("Name: " + txtname.Text);  
    sb.AppendLine("Mobile Number: " + txtmbno.Text);  
    sb.AppendLine("Email:" + txtemail.Text);  
    sb.AppendLine("Drop Downlist Name:" + ddllinksource.SelectedValue.ToString());  
    msg.Body = sb.ToString();  
    Attachment attach = new Attachment(Server.MapPath("Folder/" + ImgName));  
    msg.Attachments.Add(attach);  
    SmtpClient SmtpClient = new SmtpClient();  
    SmtpClient.Credentials = new System.Net.NetworkCredential(userName, password);
    SmtpClient.Port = 587;   
    SmtpClient.Host = "smtp.office365.com"; 
    SmtpClient.EnableSsl = true;  
    SmtpClient.Send(objMailMessage);  
}  

Email Credentials

  • userName and password are strings that store the sender's email credentials.

Creating the Mail Message

  • MailMessage msg is instantiated with sender and receiver email addresses.
  • msg.Subject sets the subject of the email.
  • StringBuilder sb is used to build the email body dynamically, appending various text lines (like name, mobile number, etc.).

Adding an Attachment

  • An Attachment object is created by specifying a file path.
  • This attachment is added to the msg.Attachments collection.

Configuring the SMTP Client

  • A new SmtpClient object is instantiated.
  • The client's credentials are set using the sender's email credentials.
  • The SMTP server details, like port number and host, are configured, and SSL is enabled.

Sending the Email

  • SmtpClient.Send(objMailMessage) is called to send the email. However, this seems to be a typo as the correct object should be msg and not objMailMessage.

Conclusion

The sendEmail method provides a basic understanding of how to send emails with attachments in C#. However, for production-level code, enhancements like secure credential storage, dynamic SMTP settings, and comprehensive error handling are crucial. Additionally, it's important to correct the typo in the Send method call.


Similar Articles