Send Email by WebService

2019-04-14 18:03发布

问题:

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

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

Let me know if any comment.

Thanks.

回答1:

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.