EWS Managed API: how to set From of email? - c#

I'm using EWS Managed API to sending email. Account "account#domain.com" have permissions "Send as" to use "sender#domain.com" mailbox to send messages (from Outlook, it's work fine).
But I try from code - it's not work, in mail i'm read in the field "From" "account#domain.com".
....
EmailMessage message = new EmailMessage(service);
message.Body = txtMessage;
message.Subject = txtSubject;
message.From = txtFrom;
....
message.SendAndSaveCopy();
How to make sending mail on behalf of another user? :)

It's been a while since I fiddled with the same thing, and I concluded that it isn't possible, in spite of having "Send as" rights.
Impersonation is the only way to go with EWS, see MSDN:
ExchangeService service = new ExchangeService();
service.UseDefaultCredentials = true;
service.AutodiscoverUrl("app#domain.com");
// impersonate user e.g. by specifying an SMTP address:
service.ImpersonatedUserId = new ImpersonatedUserId(
ConnectingIdType.SmtpAddress, "user#domain.com");
If impersonation isn't enabled, you'll have to supply the credentials of the user on behalf of whom you want to act. See this MSDN article.
ExchangeService service = new ExchangeService();
service.Credentials = new NetworkCredential("user", "password", "domain");
service.AutodiscoverUrl("user#domain.com");
Alternatively you can simply specify a reply-to address.
EmailMessage mail = new EmailMessage(service);
mail.ReplyTo.Add("user#email.com");
However, "Send as" rights do apply when sending mail using System.Net.Mail, which in many cases will do just fine when just sending e-mails. There are tons of examples illustrating how to do this.
// create new e-mail
MailMessage mail = new MailMessage();
mail.From = new MailAddress("user#domain.com");
mail.To.Add(new MailAdress("recipient#somewhere.com"));
message.Subject = "Subject of e-mail";
message.Body = "Content of e-mail";
// send through SMTP server as specified in the config file
SmtpClient client = new SmtpClient();
client.Send(mail);

i think you should use the Sender property so the your code should look like:
EmailMessage message = new EmailMessage(service);
message.Body = txtMessage;
message.Subject = txtSubject;
message.Sender= txtFrom;
....
message.SendAndSaveCopy();

Related

Mailbox unavailable. The server response was: sorry, no mailbox here by that name (#5.1.1)

Hi I am developing web application in mvc5. I have email notifications to send it to our customers. I am using below details to send emails. I have hosted application with ssl mode. Port is 25, smtpServer is mail.ourdomain.com and email is alert#ourdomain.com. We use below code to send emails.
string AdminEmail = ConfigurationManager.AppSettings["AdminEmail"].ToString();
MailMessage mail = new MailMessage();
mail.To.Add(emailid);
mail.Bcc.Add(AdminEmail);
mail.From = new MailAddress(MailID);
mail.Subject = Subject;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(hostserver);
smtp.Credentials = new System.Net.NetworkCredential(MailID, Password);
smtp.Send(mail);
I found in the error log and there is Mailbox unavailable. The server response was: sorry, no mailbox here by that name (#5.1.1) May i know the root cause of this problem. Any help would be appreciated. Thank you.
This is because you have not created the object of MailAddress correctly.
Please see below way of creating mail address:
Message = new MailMessage();
Message.From = new MailAddress(UseremailId, "Your Application");
this will resolve the above issue.

SendGrid SMTP integration issue

I am trying to integrate SendGrid in ASP.NET MVC application using SmtpClient and MailMessage methods on Azure.
Code:
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.Subject = "Subject";
message.To.Add("To#MyDomain.com");
message.Body = "Body";
message.From = new MailAddress("From#MyDomain.com", "From Name");
SmtpClient client = new SmtpClient("smtp.sendgrid.net");
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("??", "SG.******");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Port = 587; // I have tried with 25 and 2525
client.Timeout = 99999;
client.EnableSsl = false;
client.Send(message);
I end up with this issue both from C# console application and ASP.NET MVC application on Azure VM:
System.Net.Mail.SmtpException: Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
As per the documentation avlb on SendGrid site: https://sendgrid.com/docs/Classroom/Basics/Email_Infrastructure/recommended_smtp_settings.html
The UserName and Password has to : Use the string “apikey” for the SMTP username and use your API key for the password.
I have tried -
SendGrid UserName with which I login to their portal
The API Key from this page https://app.sendgrid.com/settings/api_keys
The password which starts with SG* which is as per their support team.
Any suggestions what am I missing or what which UserName/APIKey should I be using?
Tx!
The link says: Use the string “apikey” for the SMTP username and your API key for the password.
https://docs.sendgrid.com/for-developers/sending-email/v2-csharp-code-example#using-nets-built-in-smtp-library
The username was supposed to be "apikey" and not the actual "api key or api name"
client.Credentials = new NetworkCredential("apikey",
"<Your API Key which starts with SG.*>");
Adding "apikey" (facepalm) fixed my problem.
According to your description, I guess you may not add the VM outbound role for port 587.
I suggest you could follow below steps to add the role.
Find the network in azure vm portal.
Then find add outbound rule.
3.Add 587 port to outbound role.
Update:
I suggest you could try to use sendgrid SDK to do this.
I have create a test console application, it works well in my side.
Library: SendGrid
Codes as below:
var client = new SendGridClient("sendgridkey");
var from = new EmailAddress("send email address", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("To email address", "Example User");
var plainTextContent = $"Name : aaaa";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
client.SendEmailAsync(msg).Wait();
int i = 0;

How do I send an email with Gmail and SmtpClient when the sending account uses two factor authentication?

SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential =
new NetworkCredential("sender#gmail.com", "password");
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("sender#gmail.com");
smtpClient.EnableSsl = true;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = "your subject";
//Set IsBodyHtml to true means you can send HTML email.
message.IsBodyHtml = true;
message.Body = "<h1>Hello, this is a demo ... ..</h1>";
message.To.Add("receiver#gmail.com");
try
{
smtpClient.Send(message);
}
catch (Exception ex)
{
//Error, could not send the message
ex.ToString();
}
// The thing is that this code works fine for gmails without phone number protection. Exception occurs when using this code with gmails that are protected(verified) via the client phone number.
One of the solution is to use a remote server to access clients mails.
Now my question is there another method to solve this issue ? other than third parties.
If I understand you correctly, you're saying the Google account is using two-factor authentication.
If that's the case, you need to create an Application Password for this. Go to https://security.google.com/settings/security/apppasswords once logged in as the account you want to two-factor auth with.
In the list, under Select App choose "Other" and give it some name. Click Generate, and write this password DOWN cause you will only ever see it ONCE. You will use this in your authentication. It will be 16-characters long and the spaces don't matter, you can include them or omit them. I included them here just because.
NetworkCredential basicCredential =
new NetworkCredential("sender#gmail.com", "cadf afal rqcf cafo");
MailMessage message = new MailMessage();

From Address Shows NetworkCredential User Email

I have made an web application for sending e-mail. It works fine.
The problem is receiver end - Receiver shows NetworkCredential User Email as From Email.
And the email provided as From Email doesn't exist.
i want to show the suplied email not the networkcredential user email to the receiver.
sample code-
using System.Net.Mail;
MailMessage oMsg = new MailMessage();
oMsg.From = new MailAddress("sender#somewhere.com","Diplay Name");
oMsg.To.Add(new MailAddress("recipient#somewhere.com"));
oMsg.Subject = "Send Using Web Mail";
oMsg.Body ="Hi..";
System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient("host", port_no);
System.Net.NetworkCredential nc = new System.Net.NetworkCredential("user", "password");
s.EnableSsl = true;
s.UseDefaultCredentials = false;
s.Credentials = nc;
s.Send(oMsg);
The receiver gets from email is "user" but i want to show "sender#somewhere.com".
I think you need to update the Display name of the e-mail address that you send from.
Update oMsg.From = new MailAddress("sender#somewhere.com"); to be oMsg.From = new MailAddress("sender#somewhere.com","sender#somewhere.com");
MailAddress has an overload which allows you to pass is a display name for the given mail addres e.g. new MailAddress("sender#somewhere.com", "Display Name");
Some mail services (such as google), override the .FROM value, and will always use the ENVELOPE value, which is the NetworkCredential username.
I have a feeling that is what you are seeing.

How to set From Address to any email other gmail in ( Sending Email in .NET Through Gmail )?

In this post Sending Email in .NET Through Gmail we have a code to send email through gmail, in the send mail we find from Field contain gmail account that I used
I use the same code but by changing the From Address to any email I want ans set gmail address in Credentials as bellow
var fromAddress = new MailAddress("AnyEmai#mailserver.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("from#gmail.com", fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
But in the sent email gmail account still appear in From Address and AnyEmai#mailserver.com not appear ... is there any way to do that ?
It's that way by design. You have to find another way to send outbound emails so that the return address you want shows up (I've been there, there seems to be no way to spoof the from address).
Shall you check this question change sender address when sending mail through gmail in c#
I think it is related to your inquiry.
You can import an email id in your gmail account using Mail Settings >> Accounts and Import options and that can be used for sending the mails, however if you are want to use some random email id everytime to send the mails it is not possible. Gmail will treat that as a spoofing/spam and it will reset the mail address to your original mail id before sending the mail.
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("from#gmail.com");
mail.To.Add("to#gmail.com");
mail.Subject = "Your Subject";
mail.Body = "Body Content goes here";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/file.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("from#gmail.com", "mailpassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
There are many other mail services from which you can achieve the same but not through the gmail. Checkout the blog Send email in .NET through Gmail for sending mail using different properties.
The email address needed to be verified by gmail from the account settings.
Please find my blog post for the same describing it in detail, the steps to be followed:
http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
before following all the above steps, you need to authenticate your gmail account to allow access to your application and also the devices. Please check all the steps for account authentication at the following link:
http://karmic-development.blogspot.in/2013/11/allow-account-access-while-sending.html

Categories

Resources