将包含html的smtp邮件发送到gmail帐户

时间:2010-03-13 18:28:47

标签: c# .net gmail

我发现这个小代码可以向gmail用户发送电子邮件。我希望邮件的正文包含html(例如,解码链接以使其保存与其指向的URL不同的文本。)

我正在使用c#.net 3.5。我在我的代码中使用了这些类:

  • MailMessage
  • SmtpClient

如何做到这一点?

这是我的代码的副本:

            MailMessage message = new MailMessage("me@gmail.com", WebCommon.UserEmail, "Test", context.Server.HtmlEncode("<html> <body> <a href='www.cnn.com'> test </a> </body> </html> "));
            System.Net.NetworkCredential cred = new System.Net.NetworkCredential("him@gmail.com", "myPwd");
            message.IsBodyHtml = true;

            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");

            smtp.UseDefaultCredentials = false;
            smtp.EnableSsl = true;
            smtp.Credentials = cred;
            smtp.Port = 587;

            smtp.Send(message);

谢谢!

2 个答案:

答案 0 :(得分:8)

这样的事情应该有效:

请注意,MailMessage是指System.Net.MailMessage。还有System.Web.MailMessage,我从未使用过,而且据我所知 - 已经过时了。

MailMessage message = new MailMessage();
// Very basic html. HTML should always be valid, otherwise you go to spam
message.Body = "<html><body><p>test</p></body></html>"; 
// QuotedPrintable encoding is the default, but will often lead to trouble, 
// so you should set something meaningful here. Could also be ASCII or some ISO
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
// No Subject usually goes to spam, too
message.Subject = "Some Subject";
// Note that you can add multiple recipients, bcc, cc rec., etc. Using the 
// address-only syntax, i.e. w/o a readable name saves you from some issues
message.To.Add("someone@gmail.com");

// SmtpHost, -Port, -User, -Password must be a valid account you can use to 
// send messages. Note that it is very often required that the account you
// use also has the specified sender address associated! 
// If you configure the Smtp yourself, you can change that of course
SmtpClient client = new SmtpClient(SmtpHost, SmtpPort) {
            Credentials = new NetworkCredential(SmtpUser, SmtpPassword),
            EnableSsl = enableSsl;
        };

        try {
            // It might be necessary to enforce a specific sender address, see above
            if (!string.IsNullOrEmpty(ForceSenderAddress)) {
                message.From = new MailAddress(ForceSenderAddress);
            }
            client.Send(message);
        }
        catch (Exception ex) {
            return false;
        }

对于渲染Body html而不是硬编码的更复杂的模板解决方案,例如,MvcContrib中的EMailTemplateService可用作指南。

答案 1 :(得分:3)

一种方法是创建电子邮件的备用html视图:

MailMessage message = new MailMessage();
message.Body = //plain-text version of message
//set up message...

//create html view
string htmlBody = "<html>...</html>";
htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
message.AlternateViews.Add(htmlView);

//send message
smtpClient.Send(message);