C uses smtp to send mail with attachments

  • 2020-12-07 04:11:48
  • OfStack

This article illustrates the implementation of C# using smtp to send mail with attachments. You can save string type results as attachments directly. Share to everybody for everybody reference. The specific analysis is as follows:

This saves it as an HTML file, or a text file, but other formats don't work very well

MailMessage mmsg = new MailMessage();
mmsg.Subject = " Email title ";
mmsg.Body = " Email content ";
mmsg.To.Add("accept@qq.com");// To receive your email
byte[] bytes = System.Text.Encoding.Default.GetBytes
(@"<table><tr><td width=150>1234567891234567
</td><td width=80>12345678</td></tr></table>");
MemoryStream ms = new MemoryStream(bytes);
ContentType ct = new ContentType();
// Attachment file type
ct.MediaType = MediaTypeNames.Text.Html;
// Attachment names, which can be other suffix names
ct.Name = " Name of the attachment " + DateTime.Now.ToString() + ".html";
mmsg.Attachments.Add(new Attachment(ms, ct));
//SMTP Simple Mail protocol
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
sc.Host = "127.0.0.1";// The host address
sc.Port = 25;// port
// Send email account and password
sc.Credentials = new System.Net.NetworkCredential("account", "password");
// Send email
mmsg.From = new MailAddress("account@qq.com");
sc.Send(mmsg);
// Release stream resources
ms.Close();
ms.Dispose();

Hopefully this article has helped you with your C# programming.


Related articles: