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

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

Related

Does anyone know ow to fix this issue sending SMTP messages to Gmail accounts?

I am having an issue with sending emails specifically to Gmail-related accounts, and I'll be darned if I know what the issue is. This is a C# ASP.NET project, by the way.
First, the following code works, as long as I am sending to any email account OTHER than a Gmail account:
var mail = new MailMessage {
Subject = "test email",
Body = "this is only a test",
Priority = MailPriority.High,
IsBodyHtml = true,
From = new MailAddress ( "<outbound email here>" )
};
var msgID = Guid.NewGuid().ToString();
var sentBy="<outbound mail domain>";
mail.Headers.Add ( "message-id", $"<{msgID}>");
mail.Headers.Add ( "msg-id", $"<{msgID}#{sentBy}>");
mail.To.Add ( new MailAddress ( "<recipient email>" ) );
var smtpClient = new SmtpClient("<email server address>") {
Port = 587,
Credentials = new NetworkCredential("<sender's email address>", "<password>"),
};
smtpClient.Send ( mail );
I have removed email addresses and network credentials, obviously.
The code works, because as long as I send email to a NON-Gmail account, it comes through just fine. But anything going to a Gmail-related account never arrives.
I added the two lines in the code above to add a message ID to the header based on what I read in several older posts here about some mail servers, like Gmail, rejecting email messages that didn't include them, but it has not fixed the issue, and I'm out of ideas. My ISP says the SPF record for the mail server is fine, so according to them that's not the issue.
Has anyone else encountered this recently, and if so, how did you fix it?
To clarify, the comments/answers I have received so far are appreciated, but as I stated in the OP, this is a problem with sending emails TO Gmail accounts. I am using my ISP's mail server to send them, and I am adding a message ID to the header to address what the log says, that the message is missing a message ID and won't be accepted. I can send emails to other non Gmail accounts just fine, and when I inspect the headers they show a message id. So I don't know why this continues to be an issue.
So the answer to this is that the issue was related to changes Google made to policies for sending emails to Gmail accounts, which might require adjustments to the SPF record on the sending SMTP server. That was the case in this situation - the hosting company was slow to respond (took them more than a week) and had to elevate the issue to their Tier 3 techs, but once the SPF record was fixed to account for Google's changes, all was resolved.

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).

Microsoft.Graph - How to send from shared email box with different user names?

I am currently porting code for a service from using SMTP to Office 365.
With SMTP I am able to set different user names on a mail from shared inbox using the "from" field, while retaining the shared email box address. This does not appear to be working via Office 365.
The process flow is:
Customer fills in a web form that is sent to the shared email box
The service reads the email, allocates a user to this inquiry and sends a confirmation email back to the customer from the shared box but with the user's name
Any reply from the customer comes back to the shared box for further processing
Using the Microsoft.Graph API I can send / receive emails, but I can't spoof the user's name on to the outgoing email from the shared box, it always shows (to the recipient) as the name of the shared box.
Here is the code:
try
{
var sendMessage = new Message()
{
ToRecipients = new List<Recipient> { new Recipient()
{
EmailAddress = new EmailAddress()
{
Address = "customer#customer-domain.com"
}
}
},
From = new Recipient()
{
EmailAddress = new EmailAddress()
{
Address = "shared-box#my-domain.com",
Name = "ALLOCATED USER NAME HERE"
}
},
Subject = "Test Subject",
Body = new ItemBody()
{
ContentType = BodyType.Text,
Content = "This is a test text body"
},
Attachments = attachments
};
await Client
.Users[thisUser.Id]
.SendMail(sendMessage).Request().PostAsync();
}
catch(Exception ex)
{
Debug.WriteLine(ex);
}
Graph seems to be ignoring the recipient name altogether.
Microsoft Graph doc : Automate creating, sending and processing messages suggests
The from property can be changed if the Exchange administrator has assigned sendAs rights of the mailbox to some other users. The administrator can do this by selecting Mailbox Permissions of the mailbox owner in the Azure portal, or by using the Exchange Admin Center or a Windows PowerShell Add-ADPermission cmdlet. Then, you can programmatically set the from property to one of these users who have sendAs rights for that mailbox.
I have confirmed these permissions are set in the Office 365 portal. What else could I be missing?
Similar problem on my end, and found an answer in the microsoft docs here: It doesn't work - it always picks the profile name matching the e-mail and uses it for the friendly name.
So in your case you would have to change the from-address also, not only the from-name.

Why isnt the mail I sent through SendGrid visible in my sent items? (.net core)

I tried sending mails with the help of send grid mail service using .Net core.
var client = new SendGridClient(xxxxxxxxxxxxxxxxxxxxxx);
var from = new EmailAddress("test#abc.com", "Not User");
var subject = "TestMail";
var to = new EmailAddress("test#abc.com, "Example User");
var plainTextContent = "This is body";
var htmlContent = "";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
client.SendEmailAsync(msg).Wait();
The mails sent using this code are not visible in sent items of my mail box. What is the possible solution to this? Thanks in advance.
When you send the email it uses SMTP directly to sendgrid. When you send via Google they will automatically add it to your outbox. To do the same when someone else sends the message you would have to manually place a copy of the sent message in your outbox using IMAP.
What is the possible solution to this?
You could use SendGrid's BCC option will allow you to BCC an email address, in this case your mail account, with every email sent.
Go to your SendGrid Account>Manage>Settings>Mail Settings and turn on the BCC option.
Note: With this setting turned on, you will be charged an extra email for every email you send. So reclick on Manage and you will see the popup message.
Here is Send mailbox snapshot:

Windows Phone 8 sendGridMessage Compile error

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

Categories

Resources