The following C# source code shows how to send an email with an attachment from a Gmail address . The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587 . Here using NetworkCredential for password based authentication.
public static string sendMail(string To, string Subject, string Body, string Attachments, string Filename)
{
Attachments = "The following C# source code shows how to send an email with an attachment from a Gmail or other address . The Gmail SMTP or other server name is smtp.gmail.com, smtp.office365.com or other smpt and the port using send mail is 587 . Here using Network Credential for password based authentication.";
string result = "Message Sent Successfully..!!";
try
{
string UserID = "mail@mail.com";
string Password = "password";
//Initializes a new SmtpClient.
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(UserID, Password);
MailMessage msg = new MailMessage(UserID, To);
msg.IsBodyHtml = true;
msg.Subject = Subject;
msg.Body = Body;
if (!string.IsNullOrEmpty(Attachments))
{
var memStream = new MemoryStream(GetPDF(Attachments));
memStream.Position = 0;
var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
var reportAttachment = new Attachment(memStream, contentType);
reportAttachment.ContentDisposition.FileName = Filename;
msg.Attachments.Add(reportAttachment);
}
////
client.Send(msg);
//ms.Close();
}
catch (Exception ex)
{
result = "Error";
}
return result;
}
public static byte[] GetPDF(string pHTML)
{
byte[] bPDF = null;
MemoryStream ms = new MemoryStream();
TextReader txtReader = new StringReader(pHTML);
// 1: create object of a itextsharp document class
Document doc = new Document(PageSize.A4, 25, 25, 25, 25);
// 2: we create a itextsharp pdfwriter that listens to the document and directs a XML-stream to a file
PdfWriter oPdfWriter = PdfWriter.GetInstance(doc, ms);
// 3: we create a worker parse the document
HTMLWorker htmlWorker = new HTMLWorker(doc);
// 4: we open document and start the worker on the document
doc.Open();
htmlWorker.StartDocument();
// 5: parse the html into the document
htmlWorker.Parse(txtReader);
// 6: close the document and the worker
htmlWorker.EndDocument();
htmlWorker.Close();
doc.Close();
bPDF = ms.ToArray();
return bPDF;
}
2020-01-13