C system.net.mail attachment example
Here is an example of how to send an email with attachments using the System.Net.Mail
namespace in C#:
using System;
using System.Net.Mail;
using System.Net.Mime;
class Program
{
static void Main()
{
// Create a new MailMessage object.
MailMessage mail = new MailMessage();
// Set the sender and recipient.
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
// Set the subject and body of the email.
mail.Subject = "Test email with attachment";
mail.Body = "This is a test email with an attachment.";
// Create a new Attachment object.
Attachment attachment = new Attachment("path/to/attachment.txt");
// Add the attachment to the email.
mail.Attachments.Add(attachment);
// Create a new SmtpClient object.
SmtpClient client = new SmtpClient();
// Set the SMTP server and port.
client.Host = "smtp.example.com";
client.Port = 587;
// Set the username and password for the SMTP server.
client.Credentials = new NetworkCredential("username", "password");
// Send the email.
client.Send(mail);
}
}
In this example, we create a new MailMessage
object and set the sender, recipient, subject, and body of the email. We then create a new Attachment
object and add it to the email using the Attachments
property. Finally, we create a new SmtpClient
object and set its properties to connect to the SMTP server. We then send the email using the Send
method.
You can also use the AlternateViews
property to add alternative views of the email, such as HTML and plain text. Here is an example:
// Create a new AlternateView object for the HTML version of the email.
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
"<html><body>This is the HTML version of the email.</body></html>",
MediaTypeNames.Text.Html);
// Create a new AlternateView object for the plain text version of the email.
AlternateView textView = AlternateView.CreateAlternateViewFromString(
"This is the plain text version of the email.",
MediaTypeNames.Text.Plain);
// Add the AlternateViews to the email.
mail.AlternateViews.Add(htmlView);
mail.AlternateViews.Add(textView);
In this example, we create two AlternateView
objects, one for the HTML version of the email and one for the plain text version. We then add these views to the email using the AlternateViews
property. When the email is sent, the recipient's email client will choose which version to display based on their preferences.