문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top