如何通过HTTP请求发送和发送电子邮件

时间:2019-04-04 13:23:28

标签: c# asp.net http smtp

我一直在使用ASP.NET Smtp方法发送电子邮件,到目前为止,它一直运行良好。

但是现在我正在从事的业务结构已经改变,他们正在要求进行新的更改。首先,现在应该将我的电子邮件结构发送到API电子邮件服务,而不是特定的电子邮件地址。

我已经搜索了一段时间,我想我需要使用HTTPRequest来执行此操作,但是在使用C#时我并不完全有天赋。这是我的实际代码(SMTP):

protected void Send_Button(object sender, EventArgs e)
{

    // Mailing Initialization
    System.Net.Mail.MailMessage mmsg = new System.Net.Mail.MailMessage();

    mmsg.To.Add("receiver@gmail.com");
    mmsg.Body = TextBox1.Text;

    mmsg.BodyEncoding = System.Text.Encoding.UTF8;
    mmsg.IsBodyHtml = true;
    mmsg.From = new System.Net.Mail.MailAddress("sender@gmail.com");

    System.Net.Mail.SmtpClient cliente = new System.Net.Mail.SmtpClient();

    cliente.Credentials = new System.Net.NetworkCredential("sender@gmail.com", "password");

    cliente.Port = 587;
    cliente.EnableSsl = true;

    cliente.Host = "smtp.gmail.com"; 

    try
    {
        cliente.Send(mmsg);
    }
    catch (Exception)
    {
        string message = "There is an error";
        ClientScript.RegisterStartupScript(typeof(Page), "alert", "<script language=JavaScript>if(window.confirm('" + (message) + "'))</script>");
    }
}

这当然需要改变。已为我提供了一个URL,这是我的API指导:https://apitp.trial/api/Online/Mail

协议必须为HTTPS,方法必须为POST。

我告诉你,我一直在寻找没有运气的年龄。关于如何更改邮件结构以实现此目标的任何想法?

谢谢。

1 个答案:

答案 0 :(得分:0)

因此,您的解决方案似乎已从使用SMTP协议将消息发布到邮件服务器转变为使用可接收JSON的API。

从您的评论中,我可以看到它接受这样的JSON格式:

{
  "Email": "example@example.com",
  "CustomerNumber": 123456789,
  "ExternalMessageID": "1-222",
  "CustomerName": "John Smith",
  "CampaingName": "A Campaign name",
  "Extrafields": "opcional1;opcional2"
}

我假设“ Extrafields”节点是一个字符串,而不是数组,因为它似乎具有这种格式。

要在C#中与Json一起使用,您需要将JSON.NET导入到您的解决方案中(如果还没有的话)。然后,我们可以在上面的代码上使用您现有的事件处理程序,并使用它创建以下对象:

public class MailMessage
{
    public string Email { get; set; }
    public int CustomerNumber { get; set; }
    public string ExternalMessageID { get; set; }
    public string CustomerName { get; set; }
    public string CampaingName { get; set; }
    public string Extrafields { get; set; }
}

然后,您可以使用JSON.NET将此对象序列化为JSON字符串,然后以所需的格式将其发布到您的API。但是由于您的公司还需要身份验证,因此您需要在POST请求中添加标头。我也建议您使用RestSharp来简化您的生活。

您可以使用以下类似的方法来使所有这些都运行起来:

protected void Send_Button(object sender, EventArgs e)
{
    //Creates new MailMessage Object
    MailMessage mm = new MailMessage{
        Email = "someone@example.com",
        CustomerNumber = 123456789,
        ExternalMessageID = "1-222",
        CustomerName = "John Smith",
        CampaingName = "A Campaign name",
        Extrafields = "opcional1;opcional2"
    };

    var client = new RestClient("https://apitp.trial/"); //Makes a RestClient that will send your JSON to the server
    var request = new RestRequest("Online/Mail", Method.POST); //Sets up a Post Request your your desired API address
    request.AddHeader("api........?authorization", "INSERT YOUR BASE64 STRING HERE")
    request.AddHeader("Content-type", "application/json"); //Declares this request is JSOn formatted
    request.AddJsonBody(mm); //Serializes your MailMessage into a JSON string body in the request.
    var response = client.Execute(request); //Executes the Post Request and fills a response variable
}

只需在我已指出的地方插入您的Base64加密凭据,即可在响应变量中包含一些逻辑以检查其是否已正确处理。 Response变量上面带有StatusCode,代码200将指示成功。