getting "Unknown Mailbox" error when sending email using EWS API (C#) - c#

I'm simply trying to use the Office 365 API to send an email via the "Send()" function, but am getting back Microsoft.Exchange.Webservices.Data.ServiceResponseException: Mailbox does not exist.
Here's my exchange service:
_emailExchangeService =
new ExchangeService(ExchangeVersion.Exchange2013_SP1)
{
Url = new Uri(_settings.ExchangeWebServiceEndpoint),
Credentials = new WebCredentials(_settings.AppEmailUserName, _settings.AppEmailPassword),
TraceEnabled = true,
UseDefaultCredentials = false
};
And here's the code I'm using to send the email:
public void SendEmail(MemoryStream attachment, string body, string subject, string recipients, string fromMailbox)
{
EmailMessage message = new EmailMessage(_emailExchangeService);
message.From = fromMailbox;
message.Subject = subject;
message.Body = new MessageBody(BodyType.Text, body);
message.ToRecipients.Add(recipients);
message.Attachments.AddFileAttachment("FileName", attachment);
message.Send();
}
What mailbox am I forgetting to define when sending this, the sent box? I thought the "from" field would define the mailbox for sending items. I'm just not even sure where to do that and my code looks identical to the docs.
Side note: I know the exchange service is set up correctly because if I define an inbox email address and attempt to FindItems(_inbox) on the mailbox, it works.

Related

Problem with SmtpClient in ASP.NET web app

I am having an issue with SmtpClient in an ASP.NET web application.
I have a generic function that builds an email message and then sends it. The code is as follows:
public static bool SendMessage( string fromName, string toName, string subject, string body ) {
var smtpClient = new SmtpClient("server address here")
{
Port = 587,
Credentials = new NetworkCredential("user", "pass"),
EnableSsl = false,
};
var mailMessage = new MailMessage
{
From = new MailAddress("sender", "Testing"),
Subject = subject,
Body = body
};
mailMessage.To.Add ( new MailAddress(toName, "Valued Customer") );
try {
smtpClient.Send ( mailMessage );
return true;
}
catch (Exception ex) {
var error = $"ERROR :{ex.Message}";
return false;
}
}
The problem is, I get the following error when I call it:
Mailbox unavailable. The server response was: <email address being sent to> No such user here
Naturally I removed the value in the < >, but in the original error message it is the email address of the recipient. I almost think the SMTP server believes the recipient has to be a user on the system.
What can I try next? I even hard-coded email addresses in rather than using variables, thinking maybe there was some weird issue with that, but it didn't work.
The error is telling you that the the SMTP server does not have a user with that email address (usually it has to do with security around the FROM address). The SMTP server will not send email if it does not recognize the FROM address.
Solution, change your FROM. Example:
var mailMessage = new MailMessage
{
From = new MailAddress("tester", "test#adminsystem.com"),
Subject = subject,
Body = body
};

.NET : Unable to change from in SMTP email

I'm trying to send emails in .NET over SMTP. I linked serval custom aliases to the account in office365. (For example no-reply#domain-a.com, no-reply#domain-b.com)
But the mails arrive from No-Reply#mydomain.onmicrosoft.com. Even if I pass in a custom domain in the "from" parameter.
Here is my code:
var smtpClient = new SmtpClient(_settings.Endpoint, int.Parse(_settings.Port))
{
UseDefaultCredentials = false,
EnableSsl = true,
Credentials = new NetworkCredential(_settings.UserName, _settings.Password),
};
var mailMessage = new MailMessage
{
From = new MailAddress(message.From.Email, message.From.Name),
Subject = message.Subject,
Body = message.HtmlMessage,
IsBodyHtml = true
};
foreach (var addressee in message.Tos)
{
mailMessage.To.Add(addressee.Email);
}
try
{
smtpClient.Send(mailMessage);
}
catch (Exception e)
{
_logger.LogError(e, "Error sending email");
throw;
}
As username I'm using myaccount#mydomain.onmicrosoft.com. What am I missing here?
Nothing should be wrong with the office365/domain config cause it works when I'm trying to send the mail using powershell
$O365Cred = Get-Credential #the myaccount#mydomain.onmicrosoft.com credentials
$sendMailParams = #{
From = 'no-reply#mydomain-a.com'
To = 'me#gmail.com'
Subject = 'some subject'
Body = 'some body'
SMTPServer = 'smtp.office365.com'
Port = 587
UseSsl = $true
Credential = $O365Cred
}
Send-MailMessage #sendMailParams
Both Google (GMail) and Microsoft (Office365) replace the From header with the email address of the account used to send the mail in order to curtail spoofing.
If you do not want this, then you'll need to use another SMTP server or set up your own.
I found out that it works when sending the email to my personal Gmail. Meaning that there is nothing wrong with the code, but a configuration problem in my office365 / AD domain.
Apparently the outlook "address book" automatically fills in the "from / sender" part in the email, caused because I was sending an mail to the same domain as the one used for my SMTP account. (for example me#domain-a.com and noreply#domain-a.com).

How to fix “prevented a sign-in attempt” from Gmail on server (C#)

when my asp's service sends email by IEmailSender, sometime google blocks my service. This is my configuration:
public Task SendEmailAsync(string email, string subject, string message)
{
SmtpClient client = new SmtpClient(_configuration["MailSettings:Server"])
{
EnableSsl = bool.Parse(_configuration["MailSettings:EnableSsl"]),
UseDefaultCredentials = false,
Credentials = new NetworkCredential(_configuration["MailSettings:UserName"], _configuration["MailSettings:Password"]),
Port = int.Parse(_configuration["MailSettings:Port"]),
};
MailMessage mailMessage = new MailMessage
{
From = new MailAddress(_configuration["MailSettings:FromEmail"], _configuration["MailSettings:FromName"]),
};
mailMessage.To.Add(email);
mailMessage.Body = message;
mailMessage.Subject = subject;
mailMessage.IsBodyHtml = true;
client.Send(mailMessage);
return Task.CompletedTask;
}
And google make me can not send email sometimes:
When I allow this server, my service can send email normally. After short time, google blocks me again and again.I want my service can send an email everytime no need to check mail and allow this server to use my email account. Please help me. Thanks so much.

Failed to send an EMail with body contains ip address and port no

I have create function to send an email. This function was work successful on localhost but on server its failed without any exception. I know the problem comes from my Port on IP Address.
The sample body is string body = "<p>Please click here</p>Thank You."
The problem is : between IP Address and Port.
Successful send an email if i remove :.
Do you guys have any ideas?
public void Sent(string sender, string receiver, string subject, string body)
{
using (MailMessage mail = new MailMessage(sender, receiver))
{
using (SmtpClient client = new SmtpClient())
{
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "mail.companyName.com.my";
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
client.Send(mail);
}
}
}
You are doing it right, the code to send the mail is ok (you may want to revise the function name and make the smtp host name configurable, but that is not the point here).
The e-mail delivery fails on a relay, there is no immedieate feedback (no exception) to the client about this kind of failure.
The best bet is the IncreaseScoreWithRedirectToOtherPort property set in Set-HostedContentFilterPolicy in case your mail provider is Office365, or a similar spam filter mechanism in any other mail provider that is encountered down the mail delivery chain.
You can set a reply-to address and hope that the destination server will bounce a delivery failure that gives you more information. Or have the admin of the mail server look up the logs. More information here:
https://serverfault.com/questions/659861/office-365-exchange-online-any-way-to-block-false-url-spam
Try setting the 'mail.Body' to receive a Raw Html message instead of a encoded string, like:
mail.Body = new System.Web.Mvc.HtmlHelper(new System.Web.Mvc.ViewContext(), new System.Web.Mvc.ViewPage()).Raw(body).ToString();
Or put a using System.Web.Mvc at the beginning so it gets shorter and easier to understand:
using System.Web.Mvc
mail.Body = new HtmlHelper(new ViewContext(), new ViewPage()).Raw(body).ToString();

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