I apologize if this is a dupe question, but I have not found any solid information about this issue either on this site or on others.
With that being said, I am working on an MVC 5 web application. I am following this tutorial over on ASP.net.
public async Task SendAsync(IdentityMessage message)
{
await configSendGridasync(message);
}
private async Task configSendGridasync(IdentityMessage message)
{
var myMessage = new SendGridMessage();
myMessage.AddTo(message.Destination);
myMessage.From = new System.Net.Mail.MailAddress(
"info#ycc.com", "Your Contractor Connection");
myMessage.Subject = message.Subject;
myMessage.Text = message.Body;
myMessage.Html = message.Body;
var credentials = new NetworkCredential(
Properties.Resources.SendGridUser,
Properties.Resources.SendGridPassword,
Properties.Resources.SendGridURL // necessary?
);
// Create a Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
if (transportWeb != null)
{
await transportWeb.DeliverAsync(myMessage);
}
else
{
Trace.TraceError("Failed to create Web transport.");
await Task.FromResult(0);
}
}
Each time it gets to the await transportWeb.SendAsync(myMessage) line in the above method, this error shows up in the browser:
Server Error in '/' Application.
Bad Request
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Exception: Bad Request
Line 54: if (transportWeb != null)
Line 55: {
Line 56: await transportWeb.DeliverAsync(myMessage);
Line 57: }
Line 58: else
Line 59: {
Line 60: Trace.TraceError("Failed to create Web transport.");
Line 61: await Task.FromResult(0);
Line 62: }
I signed up for a free account over at https://sendgrid.com/, using the "Free Package Google", giving me 25,000 monthly credits. The account has been provisioned.
I have tried a bunch of things so far including: disabling SSL, putting username/password directly in the code instead of pulling them from the Resources.resx file, specifying the SMTP server inside the NetworkCredential object, and also tried changing DeliverAsync(...) to Deliver().
I tried explicitly setting the subject instead of using message.Subject, as this post suggested. I also tried HttpUtility.UrlEncode on the callbackUrl generated in the Account/Register method as suggested here. Same results, unfortunately.
Does anyone happen to have some insight as to what might be causing this to not function correctly?
I ended up using the built-in SmtpClient to get this working. Here is the code that I am using:
private async Task configSendGridasync(IdentityMessage message)
{
var smtp = new SmtpClient(Properties.Resources.SendGridURL,587);
var creds = new NetworkCredential(Properties.Resources.SendGridUser, Properties.Resources.SendGridPassword);
smtp.UseDefaultCredentials = false;
smtp.Credentials = creds;
smtp.EnableSsl = false;
var to = new MailAddress(message.Destination);
var from = new MailAddress("info#ycc.com", "Your Contractor Connection");
var msg = new MailMessage();
msg.To.Add(to);
msg.From = from;
msg.IsBodyHtml = true;
msg.Subject = message.Subject;
msg.Body = message.Body;
await smtp.SendMailAsync(msg);
}
Even though it doesn't use SendGrid's C# API, the messages still show up on my SendGrid dashboard.
It might be a problem with your credentials.
If you signed up with SendGrid through Windows Azure, then you need to do the following:
Log in to your Azure Portal
Navigate to the Marketplace
Locate and click on the SendGrid application
Down at the bottom, click on Connection Info
Use the Username and Password listed.
I was initially under the impression that I was to use my Azure account password until I found this. Hope this corrects your problem like it did for me.
Check that you are using the correct "username" as the "mailAccount" setting.
This should be your sendgrid username, NOT the email address of the account you are trying to send from.
I had created an SendGrid account via Azure,
I fixed this by setting these values in my Web.Config file:
<add key="mailAccount" value="azure_************#azure.com" />
<add key="mailPassword" value="[My Azure Password]" />
to my azure username and password. the username I found from the Azure Dashboard, I navigated to SendGrid Accounts >> [Clicked the Resource I had Created] >> Configurations. The password was the same one I set up the Azure account with.
I also faced this issue. solved by adding textcontent and htmlcontent. Before i was sending empty string.now its working
code below
var client = new SendGridClient(_apiKey);
var from = new EmailAddress(_fromEmailAddress, _fromName);
var to = new EmailAddress("devanathan.s#somedomain.com", "dev");
var textcontent = "This is to test the mail functionality";
var htmlcontent = "<div>Devanathan Testing mail</div>";
var subject = "testing by sending mail";
var msg = MailHelper.CreateSingleEmail(from, to, subject, textcontent, htmlcontent);
var response = await client.SendEmailAsync(msg);
I got the same error. All I had to do was to copy the appsettings in webconfig(see below) and paste it into the OTHER webconfig file (there are 2 of them in asp.net project).
<add key="webpages:Version" value="3.0.0.0" />
<add key="mailAccount" value="xxUsernamexx" />
<add key="mailPassword" value="Password" />
I had the same problem and the problem was that I had the same email on TO and BCC field. Hope it helps others..
I had the same problem, happened to have misspelled the name of the config value for the mailAccount (put mainAccount instead of the mailAccount).
NetworkCredential credential = new NetworkCredential(ConfigurationManager.AppSettings["mailAccount"], ConfigurationManager.AppSettings["mailPassword"]);
Web transportWeb = new Web(credential);
The config value was coming back as null but the exception wasnt raised and the empty username was assigned instead. Basically, put the breakpoint on the line "Web transportWeb = new Web(credential);" and see what username/password you are actually passing in credential, and see also the nevada_scout's answer.
The company domain you have registered in SendGrid should be used to call the MailAddress API. Thus, if your company web site you are registering in SendGrid is www.###.com you should use:
var from = MailAddress("info####.com", "Your Contractor Connection")
Related
I'm trying to resume a conversation between a bot and a user from a Web Job, and I'm getting an Unauthorized Exception.
I can successfully reply to a conversation in my MessagesController class, but when I try to run the following code in my Web Job, I get the following exception:
private static async Task SendAlertToUser(ChannelAccount botAccount, LipSenseUser user, AlertFlags alert, string extra)
{
Console.WriteLine($"Sending alert to user: {user.Name}");
var sb = new StringBuilder(GetTextFromAlert(alert));
if (!string.IsNullOrEmpty(extra))
{
sb.AppendLine();
sb.Append(extra);
}
var userAccount = new ChannelAccount(user.ChannelId, user.Name);
var connector = new ConnectorClient(new Uri(user.ChannelUri));
var message = Activity.CreateMessageActivity();
message.From = botAccount;
message.Recipient = userAccount;
var conversation = await connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);
message.Conversation = new ConversationAccount(id: conversation.Id);
message.Locale = "en-Us";
message.Text = sb.ToString();
await connector.Conversations.SendToConversationAsync((Activity)message);
}
And the exception is:
Exception:System.UnauthorizedAccessException
Authorization for Microsoft App ID 58c04dd1-1234-5678-9123-456789012345 failed with status code Unauthorized and reason phrase 'Unauthorized'
When I inspect the connector's Credentials, I see that everything is correct. I've set a breakpoint in my MessagesController and inspected the connector's Credentials from there, and everything is identical.
Also, when I look at the IntelliTrace, I see the following messages:
My user.ChannelUri is "https://facebook.botframework.com", which I pulled off of the user when they initialized the conversation. Is that not the correct Uri?
Is there anything else I need to do to send a message? My App.config appSettings looks like this:
<appSettings>
<add key="BotId" value="MyBotName" />
<add key="MicrosoftAppId" value="58c04dd1-1234-5678-9123-456789012345" />
<add key="MicrosoftAppPassword" value="5xyadfasdfaweraeFAKEasdfad" />
<add key="AzureWebJobsStorage" value="DefaultEndpointsProtocol=https;AccountName=BLAH;AccountKey=THIS IS A KEY" />
</appSettings>
Answer from Bot Framework Team on a different channel:
You need to add a call to:
MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
This is done automatically when you are replying to a message, but for
proactive messages from another process you need to do this.
Good day to everyone. I've writen a project based on asp.net mvc3. Part of project is based on sending emails from my application.
public void SendEmail(string address, string subject, string message, int id)
{
string email = "emailname#gmail.com";
string password = "somepassword";
var loginInfo = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
msg.Attachments.Add(new Attachment(Server.MapPath("~/Content/StudentPdf/student" + id + ".pdf")));
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}
This code works locally, perfectly sending emails. But when I upload this to the hosting, it causes an error
the SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication Required.
I've tried to change port to 465, but then it will be get me an tcp_ip error on the hosting. And one more: and when users try to send emails from this mailbox google tell me that suspicious activity on the application. It's because my hosting in one country and I am in another country.
I have no idea what I have to do next. I've tried googling and found something about 2 level registration, but don't understand how I need implement it in my method.
I'm using arvixe hosting. Maybe others have the same problems?
Please login into your gmail account manually and allow the IP of your hosting under gmail settings.Thats why i think its working perfectly on your local.
Same happened with me and after doing this there was no problem.
I am hitting a wall with reCaptcha.net
Some background -
I am using reCaptcha-dotnet v1.0.5 which I got from http://code.google.com/p/recaptcha/downloads/list?q=label:aspnetlib-Latest.
I was able to develop a site and make it work locally with reCaptcha validation. When I deploy it to the server (the site is hosted on 1and1.com), I am getting the error below -
The operation has timed out
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The operation has timed
out
I have checked the google forums which advise to have the server allow outbound connections from Port 80. I tried to explain this to the support guy at 1and1.com but I don't think he has a clue at all.
Other than the above, is there anything I could do code-wise to resolve this? Has anybody figured a solution for this?
Appreciate any kind of advise!
This is the code I use for mail configuration and Recaptcha proxy for a web site that is hosted on 1and1 :
1- Web.config (only works if put there !)
<system.net>
<mailSettings>
<smtp from="mail#domain.com">
<network host="smtp.1and1.com" port="25" userName="mymail#domain.com" password="mypassword"/>
</smtp>
</mailSettings>
<defaultProxy>
<proxy usesystemdefault = "false" bypassonlocal="false" proxyaddress="http://ntproxyus.lxa.perfora.net:3128" />
</defaultProxy>
</system.net>
2- Inside a dedicated action in mycontroller :
// ouside the action I've defined the response
private class gapi {public bool success{get;set;}}
public bool SendMail(string firstname, string lastname, string email, string message, string grecaptcha)
{
SmtpClient smtp = new SmtpClient("smtp.1and1.com");
MailMessage mail = new MailMessage();
mail.From = new MailAddress(email);
mail.To.Add("mail#domain.com");
mail.Subject = firstname + " " + lastname;
mail.Body = message;
try
{
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["secret"] = "6LcEnQYTAAAAAOWzB44-m0Ug9j4yem9XE4ARERUR";
values["response"] = grecaptcha;
values["remoteip"] = Request.UserHostAddress;
var response = client.UploadValues("https://www.google.com/recaptcha/api/siteverify","POST", values);
bool result = Newtonsoft.Json.JsonConvert.DeserializeObject<gapi>((Encoding.Default.GetString(response) as string)).success;
if(!result) return "Something is wrong)";
}
//... verify that the other fields are ok and send your mail :)
smtp.Send(mail);
}
catch (Exception e) { return "Something is wrong)"; }
return "Okey :)";
}
Hope this helps.
Finally got the solution, I got the correct proxy server address from 1and1 and used that. reCaptcha works great now.
Also, for some reason, setting the proxy value in the code using the IWebProxy property of the reCaptcha control did not work. I had to add the tag in web.config under .
Recently somebody answered me on this site, that this method can send email from .net application:
public static void SendEmail(bool isHTML, string toEmail, string fromEmail, string subject, string message)
{
var sm = new SmtpClient("smtp.mail.ru");
sm.Credentials = new NetworkCredential("MyLogin", "MyPass");
var m = new MailMessage(fromEmail, toEmail) { Subject = subject, Body = message };
if (isHTML)
{
m.IsBodyHtml = true;
}
sm.Send(m); // SmtpException
}
It is true. But now I want to use this method from Asp.Net WebService, but I have SmtpException at last string. Why? And do I send email from web service.
So the problem is not with your code, rather the transaction with the SMTP server is failing for some reason. If you have access to the SMTP server, check its logs. Otherwise you might have to use a sniffer like WireShark to figure it out.
To verify this, you can try using a different mail server, assuming you have proper access to that server it should send the mail properly.
I have to send mail using C#. I follow each and every step properly, but I cannot send mail using the code below. Can anybody please help me to solve this issue? I know it's an old issue and I read all the related articles on that site about it. But I cannot solve my issue. So please help me to solve this problem. The error is: Failure sending mail. I use System.Net.Mail to do it.
using System.Net.Mail;
string mailTo = emailTextBox.Text;
string messageFrom = "riad#abc.com";
string mailSubject = subjectTextBox.Text;
string messageBody = messageRichTextBox.Text;
string smtpAddress = "mail.abc.com";
int smtpPort = 25;
string accountName = "riad#abc.com";
string accountPassword = "123";
MailMessage message = new MailMessage(messageFrom, mailTo);
message.Subject = mailSubject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.Body = messageBody;
message.BodyEncoding = System.Text.Encoding.UTF8;
SmtpClient objSmtp = new SmtpClient(smtpAddress, smtpPort);
objSmtp.UseDefaultCredentials = false;
NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(accountName, accountPassword);
objSmtp.Credentials = basicAuthenticationInfo;
objSmtp.Send(message);
MessageBox.Show("Mail send properly");
If the target mail server is an IIS SMTP (or indeed any other) server then you'll have to check the relay restrictions on that server.
Typically, you either have to configure the mail server to accept incoming relay from your machine's name (if in Active Directory) or IP address. Either that, or you can make it an Open Relay - but if it's a public mail server then that is not recommended as you'll have spammers relaying through it in no time.
You might also be able to configure the server to accept relayed messages from a particular identity - and if this is website code that'll mean that you will most likely have to configure the site to run as a domain user so that the NetworkCredentials are sent over correctly.
oh friends...i got the solution.
just i used the port 26.now the mail is sending properly.
int smtpPort = 26;
anyway thanks to Zoltan
riad.