Windows Phone 8 sendGridMessage Compile error - c#

private async void sendMail(string from,string to, string subject,string text)
{
// Create network credentials to access your SendGrid account
string username = "xx";
string pswd = "xx";
MailMessage msg = new MailMessage();
NetworkCredential credentials = new NetworkCredential(username, pswd);
// Create the email object first, then add the properties.
// Create the email object first, then add the properties.
SendGridMessage myMessage = new SendGridMessage();
myMessage.AddTo("xx");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";
myMessage.From = new MailAddress(from);
// Create an Web transport for sending email.
var transportWeb = new SendGrid.Web(credentials );
// Send the email.
await transportWeb.DeliverAsync(myMessage);
}
My application is Windows Phone 8.1, I try to send mail via sendGrid I created an account and include libraries to code but it gives 3 error:
error CS0570: 'SendGrid.SendGridMessage.From' is not supported by the language
error CS1502: The best overloaded method match for 'SendGrid.Web.Web(string)' has some invalid arguments
error CS1503: Argument 1: cannot convert from 'System.Net.NetworkCredential' to 'string'
I have used this site"https://azure.microsoft.com/tr-tr/documentation/articles/sendgrid-dotnet-how-to-send-email/" as reference.
Do errors stem from because app is a Windows Phone app or what?
And is there any other way to send an email by declaring "from" within code?

This isn't really an answer to your question, but it's important enough I made it an answer and not a comment.
This is not a secure way to send email from a mobile device, because you are giving the code that contains the credentials to users that install. All they need to do is inspect the traffic from your app and your SendGrid API key or account is compromised.
You need to make a request to some secure backend server (or provider, e.g. Parse or Azure), and then send the email from that server rather than the client app.
If you want to debug the code though, check out the readme and example on Github. Microsoft's docs go out of date rather quickly. https://github.com/sendgrid/sendgrid-csharp

Related

ASP.NET CORE - Send email: Please log in via your web browser and then try again

I am trying to send a mail in Production with a verification link for a user registration.
For this, I have attached the credentials of the gmail account that sends the mail in my appsettings.json
APPSETTINGS.JSON:
The action of my controller that sends the mail is the following:
[HttpPost]
public async Task<JsonResult> Register(AddUserViewModel model)
{
if (ModelState.IsValid)
{
User user = await _userHelper.AddUserAsync(model, imageId);
if (user == null)
{
return Json("Email repeat");
}
string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);
string tokenLink = Url.Action("ConfirmEmail", "Account", new
{
userid = user.Id,
token = myToken
}, protocol: HttpContext.Request.Scheme);
Response response = _mailHelper.SendMail(model.Username, "App - ConfirmaciĆ³n de cuenta", $"<h1>App - ConfirmaciĆ³n de cuenta</h1>" +
$"Para habilitar el usuario, " +
$"por favor hacer clic en el siguiente enlace: </br></br>Confirmar Email");
if (response.IsSuccess)
{
return Json("Email send");
}
string message = response.Message;
return Json(message);
}
return Json("Model invalid");
}
The sendEmail method that returns a Response is as follows:
public Response SendMail(string to, string subject, string body)
{
try
{
string from = _configuration["Mail:From"];
string smtp = _configuration["Mail:Smtp"];
string port = _configuration["Mail:Port"];
string password = _configuration["Mail:Password"];
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress(from));
message.To.Add(new MailboxAddress(to));
message.Subject = subject;
BodyBuilder bodyBuilder = new BodyBuilder
{
HtmlBody = body
};
message.Body = bodyBuilder.ToMessageBody();
using (SmtpClient client = new SmtpClient())
{
client.CheckCertificateRevocation = false;
client.Connect(smtp, int.Parse(port), false);
client.Authenticate(from, password);
client.Send(message);
client.Disconnect(true);
}
return new Response { IsSuccess = true };
}
catch (Exception ex)
{
return new Response
{
IsSuccess = false,
Message = ex.Message,
Result = ex
};
}
}
The error message is the following:
"534: 5.7.14
\u003Chttps://accounts.google.com/signin/continue?sarp=1\u0026scc=1\u0026plt=AKgnsbt\n5.7.14
GCim6bqtaJeANyyQ0NvegYJS8qnYbDSCz3M0IMvB-rgIFdr1rLrIl1wbt4DkimTvNMLDl\n5.7.14
8dSGZxGuAWmDwX6gPD1T_lJ3U1e0G8EEAu6Lgt3p5gk1yJpr85Pm2mBN9nO4G33Y\u003E\n5.7.14
Please log in via your web browser and then try again.\n5.7.14 Learn
more at\n5.7.14 https://support.google.com/mail/answer/78754
t15sm12262168pjy.17 - gsmtp"
Am I sending correctly?
Should I change any gmail settings?
In the development environment the sending works without problems, any help or suggestion for me?
Directly using providers like Gmail, Outlook and similar ones is not advised because they perform checks that can disrupt your code just like you're seeing here.
This can happen without previous notice. And believe me, it will happen from time to time.
Common issues
Web-based OAuth flow
Most providers (Gmail specially) now enforce a web-based flow, from the most recent OAuth/OpenID specifications, for safer authentication/authorization.
This would be my first guess: Gmail auth (which is browser based) is simply blocking your login attempt because it wants you to use a browser and not simply submit your credentials.
There's a lot of background work done by IAM solutions to help protect users, namely called risk assessment. This, in time, might require both captcha and MFA challenges to be sent back to the user, so an API would not really work on this, that's another reason why they focus on browsers and not simply on getting the correct credentials.
Bot prevention
Email providers (specially Gmail) are great at detecting possible bots and this would be my second guess: it detected your service as a bot and put a temporary hold on your account to "protect you".
It's possible that this works on lower environments (aka: your machine and/or testing environment) and not production because of the server bot prevention system, which typically inspects IP address, user agent from the browser (if any), API call rate, authentication rate and others.
Usage rate limit
Yet another thing that can block you when doing such integration is the rate limit. Typically, 500 messages/month.
Possible solutions
Workaround - still using Gmail
To workaround this and still use Gmail, this is the way to go:
https://support.google.com/accounts/answer/185833?hl=en
It's called application password and is a different password that you generate on your account for a particular app to be allowed signing in. That will skip the OAuth and the bot validation (at least on most cases).
Proper long-term solution
The only reliable way to have this fixed is to use a proper send email service. Something like Amazon Simple Email Service, Sendgrid, or a bunch of others out there.
That's because they are created to be used by API calls and won't get in your way. You can set-up your own domain there, including SPF and DKIM keys so your recipient's email server will recognize the message as safe and indeed as coming from your (and not a random SPAM).

Bot Framework - Email Channel To send Email Via Directline C# Bot

I want to use email channel of bot framework to send email via bot if bot is unable to provide help required.
I have configured an outlook office 365 email and successfully added to the email channel of my bot.
As I have never used the email channel before I am not sure of the channel data that has to be set in case of email, I have no idea what is missing or if there's some error in reply creation.
I want to send direct email from bot to user's email id with some relevant details, user to whom email will be sent is not involved in conversation.
I am getting bad request error while trying to send the email via following code:
ChannelAccount botAccount = new ChannelAccount(
id: $"{ConfigurationManager.AppSettings["BotEmail"]}".ToLower(),
name: $"{ConfigurationManager.AppSettings["BotId"]}")
{ Id = ConfigurationManager.AppSettings["BotEmail"]};
ChannelAccount userAccount = new ChannelAccount(
id: $"{ConfigurationManager.AppSettings["UserEmail"]}",
name: "Vanjuli")
{ Id = ConfigurationManager.AppSettings["UserEmail"]};
var serviceURL = #"https://email.botframework.com/";
MicrosoftAppCredentials.TrustServiceUrl(serviceURL, DateTime.MaxValue);
using (var _connector = new ConnectorClient(new Uri(serviceURL)))
{
ConversationResourceResponse conversationId = await _connector.Conversations.CreateDirectConversationAsync(botAccount, userAccount);
IMessageActivity reply = Activity.CreateMessageActivity();
reply.From = botAccount;
reply.Recipient = userAccount;
ConversationAccount conversationAccount = new ConversationAccount(id: conversationId.Id);
reply.Conversation = new ConversationAccount(id: conversationId.Id);
reply.Text = "This is dummy text of an email!";
reply.Locale = "en-Us";
await _connector.Conversations.SendToConversationAsync((Activity)reply);
}
I would also like to send attachments via email and send email to a group (service desk or group of email ids), is it possible to do so via email channel from a bot deployed on website or are there any challenges or risks ?
According to Microsoft documentation bot receives all emails from the registered mail and can reply to any email but what I am trying to achieve is sending email explicitly which is not a reply to any previous mail. Is something like this possible for a bot which is not solely an email chatbot or is deployed on a website?
While the intent is admirable, the approach is not recommended at all, and was not intended to mix the channels in such a manner.
Nicholas is correct; if you want to showcase multiple channels, it's best to not have them in a single

Is it possible to send an email programmatically without using any actual email account

I'm thinking of implementing "Report a bug/Suggestions" option to my game, however I am not quite sure how I could get that working. I do not have my own server or anything, so I can't just send the text that user has written to there.
The only way I came up with is that the client would write a message and I would send it to an email account where I could read them. However, I do not want that users would need to send the reports through their personal accounts. I am not quite sure how I could implement this and googling didn't bring up any good suggestions.
I haven't done a lot of network stuff, so I'd really appreciate it if you could explain ( possibly even in code ) the process step-by-step.
I am using C# and the game is being programmed for Windows Phone 7.
Yes, it is absolutely possible to do that. From a relatively low-level perspective, you need to:
Resolve the MX (mail-exchanger) server for the e-mail account you want to send to.
Open a socket to the MX server.
Send the appropriate SMTP commands to cause the e-mail message to be delivered to your recipient account. You essentially have the freedom to set the "from" address to be any arbitrary thing you want.
SMTP is a very simple/human-friendly protocol, so it's not a massive effort to do all of that by hand. At the same time, there are prebuilt libraries that will handle all of that for you (except possibly the resolution of the recipient's MX server).
Note that emails sent this way are more likely to be filtered out as spam (generally because the sender's IP/hostname is not going to match whatever domain you put on the outgoing e-mail address you decide to use).
Also note that since you can set the "from" address to anything, you have the option of asking the user if they want to provide their actual contact address, and if they do you can make that the "from" address so that you can actually get back in touch with them if necessary.
You don't need to use email at all. Consider using an error reporting service like sentry or airbrake.
These services have clients that you embed in your program; which automatically log your errors, including any debugging information/stacktrace; and notify you by email when your application reports a problem.
Usually you integrate the app's API into your own error handling mechanism. At the point of an error, the client will capture your debugging information, you can popup a modal asking user for information like "what were you doing when this error happened?", save that as part of your error response that is sent back to the service.
Since the app works over HTTP, you don't need any special ports to be open. It is easier and more helpful than having users send you emails with "it doesn't work!!", and you don't have to deal with email sending headaches.
I recently wrote an article on this: Sending email with C#
You basically have two choices, either you send it using an SMTP-client, this means that you have to have a SMTP-server and be able to connect to port 25 (if you're not using an external SMTP, then you have to manage that by yourself). Or you can use an external email provider, such as:
AlphaMail
SendGrid
Mandrill
If you're using AlphaMail you can send emails in the following way:
IEmailService emailService = new AlphaMailEmailService()
.SetServiceUrl("http://api.amail.io/v1/")
.SetApiToken("YOUR-ACCOUNT-API-TOKEN-HERE");
var person = new Person()
{
Id = 1234,
UserName = "jdoe78",
FirstName = "John",
LastName = "Doe",
DateOfBirth = 1978
};
var response = emailService.Queue(new EmailMessagePayload()
.SetProjectId(12345) // ID of AlphaMail project (determines options, template, etc)
.SetSender(new EmailContact("support#company.com", "from#example.com"))
.SetReceiver(new EmailContact("Joe E. Receiver", "to#example.org"))
.SetBodyObject(person) // Any serializable object
);
Another thing that differs from just building HTML and sending it with an SMTP-client is that with AlphaMail you have the ability to edit your emails outside your code directly in a GUI. You can also easily create highly dynamic templates using AlphaMail's templating language Comlang.
<html>
<body>
<b>Name:</b> <# payload.FirstName " " payload.LastName #><br>
<b>Date of Birth:</b> <# payload.DateOfBirth #><br>
<# if (payload.Id != null) { #>
Sign Up Free!
<# } else { #>
Sign In
<# } #>
</body>
</html>
So this is my thought, why don't you have the email sent to you...as you?
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name"); //Both the email addresses would be yours
var toAddress = new MailAddress("to#example.com", "To Name"); //Both the email addresses would be yours
const string fromPassword = "fromPassword";
const string subject = "There name or whatever";
const string body = "Errors ect....";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
code from here
All they would see would be the submit button so they wouldn't have all your personal username/password, also you should prolly set up a dummy account to have them sent to even if it just then forwards them to your real email account.
Another way to achieve this would be to host a WCF Service which takes in your Message and stores in db or /sends email. One downside of this is you'll need a web server to do this.
Try following code this might help you :
Dim objCDOMail
Set objCDOMail = Server.CreateObject("CDONTS.NewMail")
objCDOMail.From = "sender#domain.com"
objCDOMail.To = "receiver#domain.com"
objCDOMail.Subject = "Test Mail Script"
objCDOMail.BodyFormat = 0
objCDOMail.MailFormat = 0
objCDOMail.Body = "Testing Mail from Test Script"
objCDOMail.Importance = 1
objCDOMail.Send
Set objCDOMail = Nothing

Email Sender App with Images on Local Machine

I have a small email application that lets a user build a message from checkboxes and then send the message as an email. I am trying to add an image to the email, i.e. a logo or signature. The application worked fine but as I was reseaching getting the images into the email, I found that I should be using System.Net.Mail instead of Interop. So I changed my email class to the code below. Now I'm not recieving the emails. I'm assumeing this is because the code is set-up for a server and I just want to run this on my local machine. This is just something I'm playing with to help me understand some concepts so real world use is not going to be a factor. I just want to be able to test my little program on my Outlook email account locally. My code is as follows...
using System;
using System.Net.Mail;
using System.Net.Mime;
namespace Email_Notifier
{
public class EmailSender:Notification
{
string emailRecipient = System.Configuration.ConfigurationManager.AppSettings ["emailRecipient"];
public void SendMail(string message)
{
try
{
string strMailContent = message;
string fromAddress = "MyApp#gmail.com";
string toAddress = emailRecipient;
string contentId = "image1";
string path = (#"C:Libraries/Pictures/Logo.gif");
MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
mailMessage.Subject = "Email Notification";
LinkedResource logo = new LinkedResource( path , MediaTypeNames.Image.Gif);
logo.ContentId = "Logo";
// HTML formatting for logo
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:Logo/><br></body></html>" + strMailContent, null, MediaTypeNames.Text.Html);
av1.LinkedResources.Add(logo);
mailMessage.AlternateViews.Add(av1);
mailMessage.IsBodyHtml = true;
SmtpClient mailSender = new SmtpClient("localhost");
mailSender.Send(mailMessage);
}
catch (Exception e)
{
Console.WriteLine("Problem with email execution. Exception caught: ", e);
}
return;
}
}
}
You specify mailSender = new SmtpClient("localhost");.
Have you set up an SMTP server on your local machine? If not, you will need to do so to use SmtpClient. Otherwise, specify a hostname other than localhost, perhaps using your Gmail account as specified here, bearing in mind you will need to configure it for authentication and SSL.
See also the documentation for SmtpClient.
There are also one or two other issues I can see with your code - but let's deal with these after getting simple mail sending working.
if your problem is that you don't have a smtp server you are talking to on your machine, you will see an exception rather than just silently not having your email delivered (which i believe is what you are seeing given that you did not list an exception, but not completely sure). it could be that you are successfully delivering to your local smtp server, but it is failing to send the mail on. if you have the iis smtp server installed and that is what you are trying to use to send the mail, you can see failed email messages in the subdirectories of C:\Inetpub\mailroot. there is a badmail subdirectory that should have failed deliveries.
if you are on windows 7, it doesn't support the iis smtp server. an alternative for having an smtp server on your machine that doesn't actually deliver the email but does show you everything that has come through for any email address is http://smtp4dev.codeplex.com/. even if i do have the iis smtp server available in my operating system, i prefer this for development needs.

Good Sample .Net Windows service to report an error

I am writing a windows service that will be doing a lot of network communication (copy many many files in shared folders and modify database).
I need a way to notify a user (if logged on) of any exceptions/errors. My issue is do group to errors for send it (by email) to administrator address.
I am aware of event logging neither notification bubble from system tray, but the administrator not views that log, he prefers email.
The ideal component is ASP.NET Health Monitoring, but only works for IIS, and it is required a component similar for Windows Services.
Any sample application Windows Service in C# or another language in .net (with source code) about this issue ??
If you're just needing a way to send an email notification, .Net has SMTP and mail types to take care of this. Email notifications are common in software anymore and that's why the commonly used functionality has been incorporated into the base class lib.
You could use SmtpClient, MailAddress, and MailMessage objects to accomplish what you need to simply send an email notification. Of course you need to have access to an SMTP server to transmit the mail, so find out what its host address is to properly configure your application. Here are a few examples:
SmtpClient mailClient = new SmtpClient("smtp.fu.bar");
MailAddress senderAddr = new MailAddress("you#fu.bar");
MailAddress recipAddr = new MailAddress("admin#fu.bar");
MailMessage emailMsg = new MailMessage( senderAddr, recipAddr );
emailMsg.Subject = "Test email.";
emailMsg.Body = "Here is my email string which serves as the body.\n\nSincerely,\nMe";
mailClient.Send( emailMsg );
That example is just straight code, but it would be better to put it into a reusable method like this:
public void SendNotification( string smtpHost, string recipientAddress, string senderAddress, string message, string subject )
{
SmtpClient mailClient = new SmtpClient(smtpHost);
MailMessage emailMsg = new MailMessage( new MailAddress(senderAddress), new MailAddress(recipientAddress) );
emailMsg.Subject = subject;
emailMsg.Body = message;
mailClient.Send( emailMsg );
}
check this : http://www.codeproject.com/Articles/16335/Simple-Windows-Service-which-sends-auto-Email-aler
my advice if it's first time to work with windows service (because Windows Service is very hard to debug)
first make it Command Line application with c#
when you be certain with all functionality of your project move it to Windows Service

Categories

Resources