I have a SMTP server that only accepts a predefined From sender.
However, I can add a custom from header in the DATA structure to set another from (sender ) address. This is possible if I test using Telnet to compose an email message:
>helo there
>mail from:the.only.allowed.sender#mydomain.com
>rcpt to:magnus#mydomain.com
>data
From:magnus#mydomain.com
To:some.user#mydomain.com
Subject:Test
Test message
.
When this email has arrived at the recipient, the from address is magnus#mydomain.com, which is the goal.
Here's my problem.
How can I mimic this "from header" in the System.Net.Mail SMTP class?
Setting the from property fails, because that would violate the SMTP server policies.
Something like this would be great, but it doesn't work:
var fromAddress = new MailAddress("the.only.allowed.sender#mydomain.com");
var toAddress = new MailAddress("user#mydomain.com");
string subject = "Subject";
string body = "Body";
var smtp = new SmtpClient
{
Host = "my-smtp-server",
Port = 25,
DeliveryMethod = SmtpDeliveryMethod.Network
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
ReplyTo = new MailAddress("magnus#mydomain.com"),
})
{
message.Headers.Add("From", "magnus#mydomain.com"); // <---- This would be great, if it worked
smtp.Send(message);
}
Has anybody got any ideas?
PS. Writing a custom SMTP class myself, using TCP sockets, it works, but can this be done in the standard .NET classes?
Well, I should have done some experimenting before posting the question...
(But instead of deleting it, I'll leave it here if others would have the same issue).
The solution was to set both the From and Sender properties on the MailMessage object.
(I'd need to set both, otherwise it doesn't work):
var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
From = new MailAddress("magnus#mydomain.com"),
Sender = new MailAddress("the.only.allowed.sender#mydomain.com")
};
smtp.Send(message);
Related
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
};
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).
Is there any way to configure forward-to email address like replyto in System.Net.Mail.MailMessage?
If not then is there any way I can achieve that?
No, there is not.
The reason is that there is no such field defined in an email. You can see the defined fields here.
So this is not a matter of C# API, there is no way to do what you want to do, not in C# and not in other languages/frameworks.
You can do this only by doing it via Outlook (using interop)
var newItem = mailItem.Forward();
newItem.Recipients.Add("test#test.be");
newItem.Send();
the .Forward() is described here
There's no 'forwardto' in MailMessage (that's up to the user receiving the mail).
But you can send to multiple receipients at once, using either the CC or the BCC properties.
Here's an axample using CC:
public static void CreateCopyMessage(string server)
{
MailAddress from = new MailAddress("ben#contoso.com", "Ben Miller");
MailAddress to = new MailAddress("jane#contoso.com", "Jane Clayton");
MailMessage message = new MailMessage(from, to);
// message.Subject = "Using the SmtpClient class.";
message.Subject = "Using the SmtpClient class.";
message.Body = #"Using this feature, you can send an email message from an application very easily.";
// Add a carbon copy recipient.
MailAddress copy = new MailAddress("Notification_List#contoso.com");
message.CC.Add(copy);
SmtpClient client = new SmtpClient(server);
// Include credentials if the server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
Console.WriteLine("Sending an email message to {0} by using the SMTP host {1}.",
to.Address, client.Host);
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateCopyMessage(): {0}",
ex.ToString() );
}
}
Now you can send to more than one, which Works like auto forwarding.
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();
I'm trying to send emails using gmail's username and password in a Windows application. However, the following code is sending the mail to only the first email address when I collect multiple email address in my StringBuilder instance.
var fromAddress = new MailAddress(username, DefaultSender);
var toAddress = new MailAddress(builder.ToString());//builder reference having multiple email address
string subject = txtSubject.Text;
string body = txtBody.Text; ;
var smtp = new SmtpClient
{
Host = HostName,
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(username, password),
//Timeout = 1000000
};
var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
IsBodyHtml = chkHtmlBody.Checked
};
if (System.IO.File.Exists(txtAttechments.Text))
{
System.Net.Mail.Attachment attechment = new Attachment(txtAttechments.Text);
message.Attachments.Add(attechment);
}
if(this.Enabled)
this.Enabled = false;
smtp.Send(message);
What am I doing wrong, and how can I sort out my problem?
Best bet is to message.To.Add() each of your MailAddresses individually. I think early versions of .Net were happier to parse apart comma or semicolon separated email addresses than the more recent runtime versions.
I was having the same problem.
The code is actually
message.To.Add("xxx#gmail.com, yyy#gmail.com");
this one can work in .net 3.5
if you use
message.To.Add( new MailAddress("xxx#gmail.com, yyy#gmail.com"));
this won't work in .net 3.5