c#发送邮件传递字符串到正文

本文关键字:字符串 正文 | 更新日期: 2023-09-27 18:16:43

我是这样写的:post

几秒钟后意识到主体是一个常量,我不能传递字符串给它。是否有任何快速的方法来改变这个代码一点,得到我需要什么?

c#发送邮件传递字符串到正文

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

你可以这样调用它:

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

删除const位…

const string body = "Body";

变成:

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

你甚至根本不需要变量:

using (var message = new MailMessage(fromAddress, toAddress)
                     {
                         Subject = subject,
                         Body = bodyPassedIn // here!
                     })
{
    smtp.Send(message);
}