是否可以在C#中使用控制台应用程序中的发送网格?我的代码不起作用,我真的不知道为什么。你可以帮帮我吗?
using System;
using System.Net;
using System.Net.Mail;
using SendGrid;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
myMessage.From = new MailAddress("adresfrom@example.com", "It's me");
myMessage.AddTo("adressj@gmail.com");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Content of the e-mail";
var username = "my_sendgrid_username";
var password = "my_sendgrid_password";
var credentials = new NetworkCredential(username, password);
// Create a Web transport for sending email.
var transportWeb = new Web(credentials);
transportWeb.DeliverAsync(myMessage);
Console.ReadLine();
}
}
}
答案 0 :(得分:3)
关于代码的几点意见:
await transportWeb.DeliverAsync(mail).ConfigureAwait(true);
请尝试使用此修复代码,并告诉我们它是如何进行的:
var transportWeb = new Web(<your-api-key-here>);
await transportWeb.DeliverAsync(myMessage).ConfigureAwait(true);
答案 1 :(得分:1)
实际上试试这个:
static void Main()
{
SendEmail().Wait();
}
static async Task SendEmail()
{
var myMessage = new SendGridMessage();
myMessage.From = new MailAddress("from_emal");
myMessage.AddTo("to_email");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Html = "<p>Hello World!</p>";
myMessage.Text = "Hello World plain text!";
var credentials = new NetworkCredential("sendgrid_user", "sendgrid_pass");
var transportWeb = new Web(credentials);
await transportWeb.DeliverAsync(myMessage);
}
看起来你应该等待DeliveryAsync方法。在Main方法中,当您删除Wait()时,它不会发送电子邮件。如果您使用Wait(),它将发送。
答案 2 :(得分:1)
它在控制台应用程序中有效,但出于某种原因需要这样调用它:
transportWeb.DeliverAsync(msg).Wait()
答案 3 :(得分:0)
尝试使用SendGrid API并通过HttpClient连接到它:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://api.sendgrid.com");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("api_key", "YOUR PASSWORD"),
new KeyValuePair<string, string>("api_user", "USER NAME"),
new KeyValuePair<string, string>("from", "some@body.com"),
new KeyValuePair<string, string>("to", "some@body.com"),
new KeyValuePair<string, string>("subject", "Whatever"),
new KeyValuePair<string,string>("text", "You can use 'html' :)")
});
var result = client.PostAsync("/api/mail.send.json", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
Debug.WriteLine(resultContent);
}
改变你的价值观,它为我工作..