Question

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?

Was it helpful?

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");

OTHER TIPS

You remove the const bit...

const string body = "Body";

turns into:

string body = bodyPassedIn; //where bodyPassedIn = is being passed into the method

You don't even need the variable at all:

using (var message = new MailMessage(fromAddress, toAddress)
                     {
                         Subject = subject,
                         Body = bodyPassedIn // here!
                     })
{
    smtp.Send(message);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top