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

时间:2013-06-01 10:19:36

标签: c# email gmail-imap

我跟着这个:post

几秒钟后发现身体是一个常数,我不能传递一个字符串。有没有快速的方法来改变这些代码并得到我需要的东西?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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