visual-studio 通过 WebService 发送电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4142654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 12:44:00  来源:igfitidea点击:

Send Email by WebService

c#asp.netvisual-studiowinformssmtp

提问by xorpower

I have developed on Windows Application. Now i need to send an email (attachment feature included) by Web Service. How can i do that?

我在 Windows 应用程序上开发。现在我需要通过 Web 服务发送电子邮件(包括附件功能)。我怎样才能做到这一点?

Also i need to notify the email before 'n' days. ('n' days is a feature controlled by user)

我还需要在“n”天之前通知电子邮件。('n' 天是由用户控制的功能)

Let me know if any comment.

如果有任何评论,请告诉我。

Thanks.

谢谢。

采纳答案by Stefan P.

public bool Send(string toAddress, string subject, string body, bool isHtml, List<string> files)
{
    try
    {
        MailMessage mailMsg = new MailMessage();

        mailMsg.To = toAddress;
        mailMsg.Headers.Add("From", string.Format("{0} <{1}>", senderName, senderAddress));
        mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = server;
        mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = port;
        mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

        if (enableAuth)
        {
            mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
            mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = userName;
            mailMsg.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = password;
        }

        if (enableSsl)
        {
            mailMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
        }

        if (isHtml)
        {
            mailMsg.BodyFormat = MailFormat.Html;
        }

        mailMsg.BodyEncoding = Encoding.UTF8;
        mailMsg.Subject = subject;
        mailMsg.Body = body;

        for (int i = 0; i < files.Count; i++)
        {
            mailMsg.Attachments.Add(new MailAttachment(files[i]));
        }
        SmtpMail.SmtpServer = server;
        SmtpMail.Send(mailMsg);

        return true;
    }
    catch (Exception ex)
    {
        this.errorMsg = ex.Message;
        return false;
    }
}

Note that you must use System.Web.Mail for this cod to work.

请注意,您必须使用 System.Web.Mail 才能使该 cod 工作。