Sender Email Address rejected and the sender is null - c#

I have searched all over and I'm not coming up with any solutions to my problem.
I've got an Email service setup with a method SendEmail which looks like this:
public void SendEmail(List<string> message, recipientEmail)
{
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add(recipientEmail);
mailMessage.Subject("My subject");
mailMessage.IsBodyHtml = true;
mailMessage.Body = message;
var address = 123.0.0.0;
var port = 1;
using (var client = new SmtpClient(address))
{
client.Port = port;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UserDefaultCredentials = false;
client.EnableSsl = false;
client.Send(mailMessage);
}
}
When I run my code I am getting this error:
Mailbox unavailable. The server response was: Sender email address
rejected
Which is totally true, my sender is null in the mailMessage.
However, in my Web.config I am doing this:
<system.net>
<mailSettings>
<smtp from="myEmail#mailinator.com">
</smtp>
</mailSettings>
</system.net>
Which I thought should just work.
So I tried adding mailMessage.Sender = new MailAddress("myEmail#mailinator.com")
And voila, it works, but I'm baffled how my other application still works without that.
I'm doing (as far as I can tell) the exact same thing in another application for a batch process I wrote and it works perfectly fine there. When I try using all of the identical settings to that batch process in my new application I get this error. I did write the batch process 6+ months ago so perhaps I have some magic sauce going on somewhere in there, or I'm just missing something obvious here.

Related

SmtpClient Send(Mail) function timeout error

I am trying to send out an email to a mailing list that I have created, but when I run the function it just times out. I am not sure whether it is a host error or if I'm missing code or what. I am running an mvc format program on a local server.
I originally didn't have the credentials, but adding them changed nothing. Both before and after adding them all that happens is it loads for about a minute before reporting a timeout.
private void SendEmail(string sender, string[] attachments, List<string> recipients, ReleaseNotes notes, string username, string password)
{
SmtpClient client = new SmtpClient();
MailMessage mail = new MailMessage();
mail.Subject = "Software Release of VCM Version " + notes.ReleaseVersion;
mail.From = new MailAddress(sender);
mail.Body = GetEmailBody(notes);
mail.IsBodyHtml = true;
foreach (string r in recipients)
{
mail.To.Add(r);
}
foreach (string a in attachments)
{
mail.Attachments.Add(new Attachment(a));
}
client.Host = "pod51213.outlook.com";
client.Credentials = new NetworkCredential(username, password);
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(mail);
}
I am supposed to see the email appear in my inbox while the screen switches over to a screen saying email was sent. Its not giving me an actual error code. It just says operation timed out.
I was able to get the host I needed and get the function to run. The company I wrote the code for had their own host server. All I did to fix the code was delete the line that included client.Credentials, because I did not need that, and in the quotes for client.Host I replaced "pod51213.outlook.com" with "smtp.irco.com", which is the mail server for the company I built the program for.
I Think you should specify the port number
e.g.
SmtpClient("smtp.gmail.com", 587) // This for gmail

Sending email through my hotmail account and changing the 'from'

I build a web form on my website to allow visitors to send me a message. Something very basic (for my personal use). On my backend (c# .Net MVC) I use SmtpClient to send the mail. I use my hotmail account for that purpose. It works. Please note that from is equal to the username used in Credentials.
SmtpClient _client = new SmtpClient();
_client.Host = "smtp.live.com";
_client.Port = 587;
_client.UseDefaultCredentials = true;
_client.Credentials = new System.Net.NetworkCredential("ttttt#hotmail.com", "mypassword");
_client.EnableSsl = true;
_client.DeliveryMethod = SmtpDeliveryMethod.Network;
MailAddress to = new MailAddress("ttttt#gmail.com");
MailAddress from = new MailAddress("ttttt#hotmail.com");
MailMessage mail = new MailMessage(from, to);
mail.Subject = "The subject";
mail.Body = "The message";
_client.Send(mail);
When I receive the mail, the sender is equal to the receiver ( myself :) This is not ideal.
From: John Doe
To: John Doe
Subject: My subject
Message: My message
I would prefer having the visitor's email address in the sender (the from). So I try to change that but it doesn't work. I got the error message below:
System.Net.Mail.SmtpException Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message.
I understand that this is not working for security reason. I cannot send an email 'in the name of' someone else.
Before giving up, I come here in the hope of someone can suggest me an alternative.
PS: I know I can use mail.ReplyToList.Add(emailofvisitor); then when I press Reply this is the visitor's email which is used but this is not still ideal because I still see my ttttt#hotmail.com in the from field.
Hope I didn't misunderstand your request, I'm assuming you would like to change the displayed name for the sender, this is what I do in my project, Add the following to your Web.Config or App.Config file:
Fill the from part with whatever you want and it will show it as the sender name.
<system.net>
<mailSettings>
<smtp from="YourDisplayName <YourEmail>" deliveryMethod="Network">
<network defaultCredentials="false" enableSsl="true" host="hostname" port="587" userName="yourusername" password="yourpassword"/>
</smtp>
</mailSettings>
</system.net>
C# code:
SmtpClient smtpClient = new SmtpClient();
var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
MailMessage message = new MailMessage();
message.From = new MailAddress(smtpSection.From);
MailAddress to = new MailAddress("youremail#gmail.com");
message.To.Add(to);
message.Subject = "The subject";
message.Body = "The message";
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(message);

System.Net mail settings using Network Solutions hosted email

I am trying to use my email service through Network Solutions (NetSol) so that emails sent via the application come from our domains service#ourdomain address.
I cannot seem to make it work, and I am not sure it is even doable since its a webmail service which I can access in a browser using a url like http://mail.ourdomain.com.
According to their site, the smtp settings can be found here
NetSol smtp
Using that information I set up my mail settings as follows
<mailSettings>
<smtp deliveryMethod="Network">
<network host="smtp.ourdomain.com" port="587" userName="service#ourdomain.com" password="xxxxxxxx" enableSsl="true" />
</smtp>
</mailSettings>
I know the password is correct as I'm able to login to my mail in the webbrowser so I don't believe its a credentials error although the error in the method is erring on the credential piece.
private async Task SendMailMessageAsync(MailMessage msg)
{
var acct = Username;
var pwd = Password;
msg.IsBodyHtml = true;
using (var mailClient = new SmtpClient())
{
if (acct != string.Empty && pwd != string.Empty)
{
var credentials = new NetworkCredential(acct, pwd);
mailClient.Credentials = credentials; //ERRING HERE
}
await mailClient.SendMailAsync(msg);
}
}
Is anyone familiar with the proper setup for NetSol professional email?
UPDATE:
For some reason, my code edit in the answer I accepted wasn't accepted. So here is the code, in working order based on the comments in the accepted answer.
public void SendNetSolEmail()
{
var sender = "whatever#yourdomain.com";
var pass = "yourpassword";
var mailMessage = new MailMessage(sender, "sendto_emailaddress", "Hi there", "This method works fine!");
var mailClient = new SmtpClient("mail.yourdomain.com", 587)
{
Credentials = new NetworkCredential(sender,pass),
EnableSsl = false, //important for Network Solutions mail
DeliveryMethod = SmtpDeliveryMethod.Network
};
mailClient.Send(mailMessage);
}
A simple working example of connecting to NetSol's smtp
System.Net.Mail.SmtpClient mailMsg = new System.Net.Mail.SmtpClient("mail.domain.com", 587);
mailMsg.Credentials = new System.Net.NetworkCredential("username#domain.com", "password");
mailMsg.SendMailAsync("username#domain.com", "someone.somewhere#somedomain.com", "Hi Someone", "Body of the email");
and the last note as I see you have ssl enabled; Here it is direct from NetSol:
Note - Make sure you are not chosing and SSL type, this option should be turned off, or "None" should be selected.

Can we send mails from localhost using asp.net and c#?

i am using using System.Net.Mail;
and following code to send mail
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
// Set the sender's address
message.From = new MailAddress("fromAddress");
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
// Set the SMTP server to be used to send the message
client.Host = "YourMailServer";
// Send the e-mail message
client.Send(message);
for Host i am providing client.Host = "localhost";
for this its falling with error
No connection could be made because the target machine actively
refused it some_ip_address_here
and when i use client.Host = "smtp.gmail.com";
i get following error
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond
i am not able to send mail through localhost.
Please help me out, i am new to c# please correct me in code where i am going wrong..?
Here is some code that works for sending mail via gmail (code from somewhere here on stackoverflow. It is similar to the code here: Gmail: How to send an email programmatically):
using (var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("yourmail#gmail.com", "yourpassword"),
EnableSsl = true
})
{
client.Send("frommail#gmail.com", "tomail#gmail.com", "subject", message);
}
For sending mail from client.Host = "localhost" you need set up local SMTP server.
For sending mail via Google (or via any other SMTP server, including your own local SMTP) you must set username, password, ssl settings - all as required by SMTP server chosen, and you need to read their help for this.
For example Google says that you need SSL, port 465 or 587, server smtp.gmail.com and your username and password.
You can assign all this values in .config file.
<system.net>
<mailSettings>
<smtp>
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="yourname#gmail.com" password="password" />
</smtp>
</mailSettings>
</system.net>
Or set to SmtpClient in code before every use:
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSSL = true;
client.Credentials = new NetworkCredential("yourname#gmail.com", "password");
Place this code inside a <configuration> </configuration> in web.config file
<system.net>
<mailSettings>
<smtp>
<network host="smtp.gmail.com" enableSsl="true" port="587" userName="youremail#gmail.com" password="yourpassword" />
</smtp>
</mailSettings>
</system.net>
then backend code
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress("email#gmail.com");
message.To.Add(new MailAddress(TextBoxEadd.Text));
message.CC.Add(new MailAddress("email#gmail.com"));
message.Subject = "New User Registration ! ";
message.Body = "HELLO";
sr.Close();
SmtpClient client = new SmtpClient();
client.Send(message);
I hope this code help you! :)
use this Line..Dont Use Port And HostName
LocalClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
I just wanted to add that Gmail now requires App Password in order to use it from other applications. Check this link. I had to find it the hard way. After I created an App Password and then I changed the NetworkCredentials to use it to send emails.

SMTP email "Service" I can include in my C# project?

I've written several programs that send email from C#. This works great in winXP, but I find it breaks in Win7. My understanding is that even though the SMTP server I'm referencing is on another computer, the sending computer needs to have the SMTP service installed (and win7 does not).
I know its possible to install a third party SMTP server, but then I'd need to do that on every computer running my programs. Instead, I'd like to include a temporary SMTP server in my project that I can use entirely from code to do the same job. Does anyone know of a library (or sample code) on how I can include a temporary SMTP server in my project?
Here is my code:
public static void sendEmail(String[] recipients, String sender, String subject, String body, String[] attachments)
{
MailMessage message;
try
{
message = new MailMessage(sender, recipients[0]);
}
catch (Exception)
{
return;
}
foreach (String s in recipients)
{
if (!message.To.Contains(new MailAddress(s)))
message.To.Add(s);
}
message.From = new MailAddress(sender);
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("PRIVATE.PRIVATE.PRIVATE", 25);
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = true;
if (attachments.Length > 0)
{
foreach (String a in attachments)
{
message.Attachments.Add(new Attachment(a));
}
}
try
{
smtp.SendAsync(message, null);
To send emails from c#, you do not need a local SMTP service. You just need the System.Net.Mail library. Using a remote SMTP server (possibly one with valid PTR settings and not one in your network to avoid being regarded as a spammer) should definitely suffice.
It may be a credentials issue. Change SendAsync to Send to see if you are getting any exceptions. Or add a handler for the Async invocation
smtp.SendCompleted += delegate(object s, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
System.Diagnostics.Trace.TraceError(e.Error.ToString());
}
};
Following changes to your code works for me in Win7
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
//smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(GoogleUserEmail, GooglePassword);
smtp.EnableSsl = true;
// smtp.UseDefaultCredentials = true;
if (attachments != null && attachments.Length > 0)
{
foreach (String a in attachments)
{
message.Attachments.Add(new Attachment(a));
}
}
try
{
smtp.Send(message);
}
I have never found an embeddable SMTP server, but both of these are close and you could probably modify them to fit your needs.
http://www.codeproject.com/KB/IP/smtppop3mailserver.aspx
http://www.ericdaugherty.com/dev/cses/developers.html
I'm going to keep looking because this is also something I'd find useful. I'll post more if I find any.
If you just use an unconfigured service to send your emails you will definitely end up in the SPAM folder due to reverse DNS and SPF checks failing. So you'll want to configure your server properly. Alternatively you can use a 3rd party service like Elastic Email. Here is Elastic Email's sample code which uses HTTP to send the mail:
public static string SendEmail(string to, string subject, string bodyText, string bodyHtml, string from, string fromName)
{
WebClient client = new WebClient();
NameValueCollection values = new NameValueCollection();
values.Add("username", USERNAME);
values.Add("api_key", API_KEY);
values.Add("from", from);
values.Add("from_name", fromName);
values.Add("subject", subject);
if (bodyHtml != null)
values.Add("body_html", bodyHtml);
if (bodyText != null)
values.Add("body_text", bodyText);
values.Add("to", to);
byte[] response = client.UploadValues("https://api.elasticemail.com/mailer/send", values);
return Encoding.UTF8.GetString(response);
}
Have you tried specifying SMTP settings in an App.config file? Something like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<specifiedPickupDirectory pickupDirectoryLocation="C:\tmp"/>
<network host="smtp.example.com"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
If you change deliveryMethod="SpecifiedPickupDirectory" then it'll just write a file representing the email that would be sent to the directory you specify.

Categories

Resources