Is .net core accepting only email address from config's MailSettings and only one can be set up? - asp.net-core

I am trying to send an email using and getting the following error:
User not local; please try a different path. The server response was:
Sender address is not valid for your login. Check your email program
settings
I have understood that the error appears because in my MailMessage object I am providing another email address for From field than the one set up in the appsettings.json
(.NET was supporting custom sender emails in MailMessage.)
The questions are:
Can I only use the email address in MailMessage.From
field that is provided in appsettings.json's MailSettings?
Can I add more than one email address to appsettings.json's MailSettings?
Is there a way to use a custom MailMessage.From email other than set up in appsettings.json's MailSettings?
MailAddress from = new MailAddress(mailRequest.FromAddress, mailRequest.FromName); // custom "form" that is causing the error
var mailMessage = new MailMessage(from, new MailAddress(mailRequest.ToAddress)) {
Subject = mailRequest.Subject,
Body = mailRequest.Body
};
await _smtpClient.SendMailAsync(mailMessage);
Thanks

Related

How to send email from any one email using Microsoft Graph

I am using microsoft graph to send email. This email I want to send from any email that exists in the Active directory.
I already have get the permission on Mail.Send and have admin consent on Azure.So all set on the Azure level for access and permission.
Now when come to code. I have searched for but I am not able to figure out how to call the Microsoft graph api to send the email. Below is the code that I have been finding when I am doing search. How I can replace the below code to send the email to anyone from anyone in Azure AD to anyone in Azure AD. Also the code for send email 'Send AS'.
await graphClient.Me.Messages
.Request()
.AddAsync(message);
The intention is the signed in user will not send email from his email
address, the email notification will be asthmatically sent by someone
else name to someone.
Then I think you wanna provide a sending email to your users, users can choose who received the email, but all the email should be sent be a specific account, such as admin#xxx.onmicrosoft.com, then you should know something about the sending email api.
As #user2250152 mentioned, await graphClient.Users["userId"], here the userId means who send the email, as your requirement is sending all emails from one specific email address, it should hardcode as admin#xxx.onmicrosoft.com.
The next is how to send the email, calling ms graph api should offer an access token, as your requirement is sending email by the application but not every user, so I'm afraid the client credential flow is a better choice so that when the scenario comes to sending email from several specific email addresses, you don't need to change the flow then. Now you need to require your tenant admin to add Mail.Send Application api permission in azure ad to use this kind of flow.
And here's the code:
using Azure.Identity;
using Microsoft.Graph;
var mesg = new Message
{
Subject = "Meet for lunch?",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "The new cafeteria is open."
},
ToRecipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new EmailAddress
{
//who will receive the email
Address = "xxx#gmail.com"
}
}
},
Attachments = new MessageAttachmentsCollectionPage()
};
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_client_id";
var clientSecret = "client_secret_for_the_azuread_app";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
await graphClient.Users["user_id_which_you_wanna_used_for_sending_email"].SendMail(mesg, false).Request().PostAsync();
You can send mail from other user this way.
var message = new Message
{
Subject = "Subject",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "Content"
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "john.doe#contoso.onmicrosoft.com"
}
}
}
};
var saveToSentItems = false;
await graphClient.Users["userId"]
.SendMail(message,saveToSentItems)
.Request()
.PostAsync();
userId is the unique identifier for the user. Instead of userId you can use userPrincipalName. The UPN is an Internet-style login name for the user based on the Internet standard RFC 822. By convention, this should map to the user's email name.
Resources:
Send mail
User resource

Is it possible to have a different sender email and configuration email to send email from MimeKit in ASP.Net Core?

I have added code which will send emails to the receiving party. As of now I need to add the same email address in "from" email and "username"(config email) to send the email else it will fail. But I wish to have different "from" email and not asking users for password and using one config mail to send email so multiple users can consume this service to send emails. Is it possible to do so?
Here is my code:
public async Task<string> Send(string from, string to, string subject, string html, string userName, string password)
{
// create message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(from));
email.To.Add(MailboxAddress.Parse(to));
email.Subject = subject;
email.Body = new TextPart(TextFormat.Html) { Text = html };
using var smtp = new SmtpClient();
smtp.Connect("smtp.live.com", 587, SecureSocketOptions.StartTls);
smtp.Authenticate(userName, password);
smtp.Send(email);
smtp.Disconnect(true);
return "Email Set";
}
Yes, but you'll need to use a private SMTP server that will accept different addresses in the From: header and the authenticate commands. None of the widely-used public SMTP servers allow this as far as I know.

Delay in sending email in ASP.NET CORE

Hi am building a web application using blazor which sends email activation link to registered users, email activation is is being sent but the problem here it takes too long(approximately 5 minutes) for the registered user to receive the activation link. here is my code.
my interface class
public interface IEmailServices
{
Task SendEmailAsync(string toAddress, string subject, string body);
}
My mail Sender Class
public class EmailSender : IEmailServices
{
public async Task SendEmailAsync(string emailDestination, string subject, string htmlMessageBody )
{
MailMessage ms = new MailMessage("myemail#domain.com", emailDestination, subject,htmlMessageBody);
ms.IsBodyHtml = true;
string user = "myemail#domain.com";
string passcode = "mypassword";
SmtpClient smtpServer = new SmtpClient("mail.domain.com");
smtpServer.Credentials = new System.Net.NetworkCredential(user, passcode);
try
{
await smtpServer.SendMailAsync(ms);
}
catch (Exception ex)
{
throw ex;
}
}
}
Here's where am sending the message
//Generate Email confirmation link
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
I want the message to be sent immediately upon registration so user can confirm email.. is there something am missing thanks in advance
You don't appear to be doing anything that would generate a huge email, so this shouldn't be taking very long. A suggestion I can make is to set up your app in a test environment, with the SMTP connection set to an email account you have access to in your configuration. (Even a gmail account would work, but you'd have to set the Gmail security appropriately.) Then, run your app in debug mode with a breakpoint at await smtpServer.SendMailAsync(ms);, and then continue (F5 in VS) forward from that call to execute SendEmail Async() and let the app continue running. This will allow confirmation that the email sent, and also give you some insight into if the issue is ahead of sending the email entirely or not. Make sure you are signed in to the email account you are testing with before you start, then hop into the email account Sent folder and check that it shows the sent email. If the email takes a long time to send, the issue is in your SMTP connection from the app. If it sends in short order but still takes forever to arrive at the recipient, it has to do with the email account(s) or the clients hooked up to them (think the Send / Receive interval in Outlook set too long), but not necessarily your application. That should help you pin the problem down so you know what you are dealing with.

Smartsheet API Email Recipients

Apologies for the basic question, but how do I add multiple recipients (email addresses) to an email object with the Smartsheet VB (uses C#) SDK?
Documentation here but cant see how to add multiples:
http://smartsheet-platform.github.io/api-docs/?csharp#email-object
The following code example shows how to specify two recipients, construct an email object, and execute the SendSheet operation using that email object. The same technique for specifying recipients and constructing the email object can be applied to other Send operations (e.g., SendReport, SendRow, etc.).
// Specify recipients
Recipient[] recipients = new Recipient[] {
new Recipient { Email = "john.doe#smartsheet.com" },
new Recipient { Email = "jane.doe#smartsheet.com" }
};
// Configure email
SheetEmail sheetEmail = new SheetEmail {
SendTo = recipients,
Subject = "Check this sheet out!",
Message = "Here's the sheet I mentioned in our meeting.",
CcMe = false,
Format = SheetEmailFormat.PDF,
FormatDetails = new FormatDetails { PaperSize = PaperSize.A4 }
};
// Send sheet via email
smartsheet.SheetResources.SendSheet(SHEET_ID, sheetEmail);

Using VB.NET to log into Windows Live Mail?

I want to make a program that tells you if you can login to an email account or not by entering their username and password into Windows Live.
It would connect to the Hotmail server and see if the user/pass combination is correct. If it can log in, it would display a label that the account is valid, if not it would say that the account is not valid.
How would I go about doing this?
Ok here's the totally incorrect code for logging in. I kind of borrowed it from sending an email:
Dim MyMailMessage As New MailMessage
MyMailMessage.From = New MailAddress(TextBox1.Text)
MyMailMessage.To.Add(TextBox1.Text)
Dim SMTP As New SmtpClient("smtp.live.com")
SMTP.Port = 25
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential("textbox1.text", "textbox2.text")
SMTP.Send(MyMailMessage) // I have no idea how to get a response here... from the live server if it gives me a correct or incorrect response...
Can someone post an example code if they have a solution to this? Because I have no idea how to make this single handingly.
dim smtp as new smtpclient("smtp.live.com",25)
dim m as new mailmessage()'message must contains from, to, etc
with smtp
.usedefaultcredentials = false 'by default this is true
.credentials = new networkcredential("usuername","password")
.enablessl = true
.ishtmlbody = true
.send(m)
'or async
'.send(m,addresof enviado)' i'm not remember well if addressof is required here
end with
public sub Enviado
msgbox("mail message sended async")
end sub
One option could be to use the WebBrowser control which would allow you to access the username and password input boxes, and would allow you to click the login button. You could then see which page the user is redirected to and that would tell you in the username/password combo is correct or not.
Use Fiddler or HTTP Analyzer to see what happens when you sign in with a Browser.
(I can give you a hand: A http post request is sent to https://login.live.com....)
All you have to do then is to mimic this request with the HttpWebRequest class in .NET.
It's important that you make your request as similar as the one from the Browser as possible.