Search code examples
c#emailgmail-imap

c# sending mail pass string to body


I was following this: post

And after a few seconds realized that the body is a constant and I can't pass a string to it. Is there any fast way to change this code a bit and get what I need?


Solution

  • public void PostMessage(string body,string subject)
            {
                var fromAddress = new MailAddress("from@gmail.com", "From Name");
                var toAddress = new MailAddress("to@example.com", "To Name");
                const string fromPassword = "fromPassword";
    
                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body,
                })
                {
                    smtp.Send(message);
                }
            }
    

    you can call it like this:

    PostMessage("MAH BODY", "SUBJECT");