I have used this code to send mails but I am not getting any error but I'm able to receive the mail. The default smtp server is also set to "127.0.0.1" as my local host in relay mail in the "inetmgr" but I'm still not able to receive the mail. I don't know where the problem is.
In emailsender.cs class this is the code:
public void SendEmail(string To, String Subject, String Body, String uname)
{
string body = "Hi " + uname + ",\n\n \t" + Body + "\n" + " \n Regards, \n LMS Team" + "\n\n\tSent at: " + DateTime.Now + " \n\n\t\t---- This is an auto generated mail. Please do not reply.";
try
{
try
{
MailMessage Message = new MailMessage();
Message.From = new MailAddress("karhik.varadarajan#asteor.com");
if (!string.IsNullOrEmpty(To))
Message.To.Add(new MailAddress(To));
Message.Subject = Subject;
Message.Body = body;
try
{
SmtpClient smtpClient = new SmtpClient("localhost");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtpClient.Port = 25;
smtpClient.UseDefaultCredentials = false;
smtpClient.Send(Message);
}
catch (System.Web.HttpException ehttp)
{
throw new Exception("Email Sending Failed", ehttp);
}
}
catch (IndexOutOfRangeException ex)
{
throw new IndexOutOfRangeException("Email Sending Failed", ex);
}
}
catch (System.Exception ex)
{
throw new Exception("Email Sending Failed", ex);
}
}
In the .aspx file:
protected void Page_Load(object sender, EventArgs e)
{
EmailSender email = new EmailSender();
email.SendEmail("karhik.varadarajan#asteor.com", "testingmail", "this is a test mail", "From");
}
If you use PickupDirectoryFromIis option, Check you C:\Inetpub\mailroot\Pickup or Queue or Badmail directory whether the EML file created or not. If it is in PickUp or Queue folder, IIS may process the file. If it is in BadMail, IIS unable to process the file.
I experienced the same issue,sometimes the organization wont allow access to send email.so i tried email relaying server. try elastic email.
If there are no error there are most likely an smpt server setup problem. Firstly, you are using localhost, not 127.0.0.1. I would recommend as a best practice to use 127.0.0.1 when calling localhost.
Even if it is a "shouldn't need too" there are no reason at all, using localhost. At least put "127.0.0.1 localhost" in windows etc\hosts file. You may also try a external SMTP host that you know ou have access to (like your isp). I know misconfigured smtp hosts CAN appear as the was sended succesfully.
However, as other already stated above, there can be a lot of other problems like access to send mail. Though, i think most errors like those will throw an error back to you.
Related
I am trying to send an email to a fake email address and get a SmtpFailedRecipientException, however when I send the email to a fake address on my company domain, no exception is thrown. I am developing in VS2015 with .NET 4.5.2 and running the console application on a Windows 7 environment.
This code works correctly and sends emails when the email addresses are valid, and it will even throw a SmtpFailedRecipientException when I try sending to an invalid gmail or hotmail address. It seems that the only time an exception isn't thrown is when I try to send to a fake address within my company domain. Our company uses Office365 and I get an 'Undeliverable' message in my inbox when I try to send to the fake address from my address.
Does anyone have an idea why this is happening? I suspect it might be a setting on the mail server, but I dont have access to the mail server to check and see. I also might just be missing something obvious and be making a rookie mistake.
// Initialize SMTP client
SmtpClient client = null;
try
{
string from = "myEmailAddress#mycompany.com", to = "fakeEmailAddress#mycompany.com";
// Build client
client = new SmtpClient("mail.mycompany.com");
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
// Create message
using (MailMessage message = new MailMessage(from, to)
{
Subject = "Test email to fake address",
Body = "This email won't be sent"
})
{
// Send message
client.Send(message);
}
}
catch (SmtpFailedRecipientException ex)
{
Console.WriteLine($"SmtpFailedRecipientException caught.{Environment.NewLine}{ex.ToString()}");
}
catch (Exception ex)
{
Console.WriteLine($"Exception caught.{Environment.NewLine}{ex.ToString()}");
}
This is my first experience with sending an email using c#. Everything I have so far I got from reading and watching videos. I currently have the code written to send an email. It creates it and displays the email with all of the information correct and ready to send. The email opens up and then I click send and it works. The problem is that I want the email to send on its own, without me having to click send.
This is my code:
static void SendEmail()
{
Microsoft.Office.Interop.Outlook.Application app = new
Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mailItem = app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mailItem.Subject = "Status of Code";
mailItem.To = "bt#outlook.com";
mailItem.Body = "Code Ran Successfully";
mailItem.Importance = Outlook.OlImportance.olImportanceHigh;
mailItem.Display(false);
}
I tried adding in
mailItem.Send;
but I kept getting an error. How else would I do this?
Referencing Microsofts documentation (https://msdn.microsoft.com/en-us/library/swas0fwc(v=vs.110).aspx), I'd recommend instead using an SMTP client (as opposed to being outlook specific).
Your code would then look something like:
public static void SendEmail()
{
string to = "bt#outlook.com";
string from = "fromAddress#outlook.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = #"Code Ran Successfully";
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in SendEmail(): {0}",
ex.ToString() );
}
}
Following code used to work but suddenly refuses to work.
private static void SendMail()
{
try
{
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.google.com", 587);
mail.From = new MailAddress("catthoor.jc#gmail.com", "Jasper.Kattoor");
mail.To.Add("YYYY");
mail.Subject = "sup";
mail.Body = "sup";
smtpServer.Credentials = new NetworkCredential("catthoor.jc#gmail.com", "XXXX");
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}
I receive the following error:
System.Net.Mail.SmtpException: Failure sending mail. --->
System.Net.WebException: The remote name could not be resolved:
'smtp.google.com'
I've also tried using hotmail instead of gmail, same error.
I can still send mails manually though.
Why would this error suddenly occur? Yesterday there were no problems with this.
That remote host name is wrong, it should be:
smtp.gmail.com
Read all about it: Send Email from Yahoo!, GMail, Hotmail (C#)
Updates: You can also ping the host name to check if it exists using command prompt
Yes, in my case I wasn't just connected to the internet.
After I connected the problem was gone.
I am trying to implement a "forgot password" method into my site. It works perfectly in debug. Using the same code and db, but published to our web server it fails when it tries to send the message.
The error that I get is:
There was an error sending you an email.
The specified string is not in the form required for an e-mail address.
The email is valid, so I have no idea why it is failing.
Because it is a live environment I cannot step through the code to see exactly where and why it is failing. I implemented db logging so I can see how far it gets before it fails and it successfully executes all code up to this point:
var smtp = new SmtpClient
{
Host = host,
Port = port,
EnableSsl = ssl,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPw)
};
using (var message = new MailMessage()
{
Subject = subject,
Body = body,
IsBodyHtml = ishtml,
From = fromAddress
})
{
foreach (MailAddress t in toCol)
{ message.To.Add(t); }
foreach (MailAddress c in ccCol)
{ message.CC.Add(c); }
foreach (MailAddress b in bccCol)
{ message.Bcc.Add(b); }
smtp.Send(message);
}
It never gets to the next db logging so it has to be failing here. In my test I have exactly one email address for the to and none for bcc and cc. When stepping through in debug it correctly loads the single email address and doesn't load any for cc and bcc. I have no idea what it is considering to be an invalid email address.
EDIT:
We use Google Apps as our mail server so both my workstation and the server have to connect. I am using the following:
Host: smtp.gmail.com
Port: 587
EnableSsl: true
Credentials: valid username and password that work in debug
EDIT 2:
To incorporate some of the suggestions from you.
The fromAddress is set earlier using values from the db like this:
DataTable ts = DAL.Notification.GetNotificationSettings();
var fromEmail = ts.Rows[0]["fromadr"].ToString().Trim();
var fromName = ts.Rows[0]["fromname"].ToString().Trim();
var host = ts.Rows[0]["server"].ToString().Trim();
var port = Convert.ToInt32(ts.Rows[0]["smtpport"]);
var ssl = Convert.ToBoolean(ts.Rows[0]["is_ssl"]);
var ishtml = Convert.ToBoolean(ts.Rows[0]["is_html"]);
var bodyTemplate = ts.Rows[0]["bodyTemplate"].ToString();
body = bodyTemplate.Replace("{CONTENT}", body).Replace("{emailFooter}","");// Needs to use the Global emailFooter resource string
var fromAddress = new MailAddress(fromEmail, fromName);
I have even tried hard coding the from address like this:
message.From = new MailAddress("websystem#mydomain.com");
I still get the error and it still fails when defining the message.
Any other suggestions on how to find and fix the problem?
ANSWER
I did not define the default from address in the web.config like this:
<system.net>
<mailSettings>
<smtp from="email#yourdomain.com">
<network host="smtp.yourdomain.com"/>
</smtp>
</mailSettings> </system.net>
So it failed at var message = new MailMessage() before I could define the correct from address.
I either needed to implement var message = new MailMessage(From,To) or provide a default from address in web.config (which is what I did)
This error can be caused by two things:
One of the email addresses your using (for message.To, message.CC or message.Bcc) is invalid, i.e. it doesn't follow the required format of someuser#somedomain.xxx.
The From address configured in Web.Config is invalid:
<system.net>
<mailSettings>
<smtp from="invalid##email">
<network host="smtp.gmail.com"/>
</smtp>
</mailSettings>
</system.net>
My recommendation is to use try/catch statements to further narrow the problem. I'd also temporarily lose the using statement for the MailMessage for easier troubleshooting.
Example:
var smtp;
try
{
smtp = new SmtpClient
{
Host = host,
Port = port,
EnableSsl = ssl,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPw)
};
}
catch (Exception exc)
{
MessageBox.Show("Error creating SMTP client: " + exc.Message);
}
var message = new MailMessage();
try
{
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = ishtml;
message.From = fromAddress;
}
catch (Exception exc)
{
MessageBox.Show("Error creating MailMessage: " + exc.Message);
}
try
{
foreach (MailAddress t in toCol)
message.To.Add(t);
}
catch (Exception exc)
{
MessageBox.Show("Error adding TO addresses: " + exc.Message);
}
try
{
foreach (MailAddress c in ccCol)
message.CC.Add(c);
}
catch (Exception exc)
{
MessageBox.Show("Error adding CC addresses: " + exc.Message);
}
try
{
foreach (MailAddress b in bccCol)
message.Bcc.Add(b);
}
catch (Exception exc)
{
MessageBox.Show("Error adding BCC addresses: " + exc.Message);
}
try
{
smtp.Send(message);
}
catch (Exception exc)
{
MessageBox.Show("Error sending message: " + exc.Message);
}
Alternatively, you could replace the various MessageBox.Show() statements with something that writes to a log file. By breaking this up you should be able to pinpoint the problem with more accuracy.
I have code,
System.Web.Mail.MailMessage oMailMessage = new MailMessage();
oMailMessage.From = strFromEmaild;
oMailMessage.To = strToEmailId;
oMailMessage.Subject = strSubject;
oMailMessage.Body = strBody;
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send(oMailMessage);
(all variables have values)
I have installed SMTP virtual services. why it is unable to send emails. why it is not working ??
EDIT
public bool SendMail(string strToEmailId, string strFromEmaild, string strSubject, string strBody)
{
try
{
System.Web.Mail.MailMessage oMailMessage = new MailMessage();
oMailMessage.From = strFromEmaild;
oMailMessage.To = strToEmailId;
oMailMessage.Subject = strSubject;
oMailMessage.Body = strBody;
SmtpMail.SmtpServer = "SERVERNAME";
SmtpMail.Send(oMailMessage);
return true;
}
catch (Exception ex)
{
return false;
}
}
I have this code. It is executing fine and is returning true, but I'm not getting any email in the inbox.
What else could be wrong?
Getting some mails in BadMail Dir at C:\Inetpub\mailroot\Badmail also in Queue Directory getting some mails here ... what does that means..??
I found that mail only can sent to gmail accounts... why it is?
As mentioned by others, your code is fine and is most likely something in your SMTP configuration or maybe your email client your sending your test emails to is marking them as spam. If it's spam, well that's easy enoughto figure out.
If it's something with the email, you can go to your mailroot folder and their will be some folders there with the email files along with a description. See if there's anything in the BadMail folder or the queue folder and open them up in notepad and view what error is given for why they weren't sent.
Determine what the error is:
try
{
SmtpMail.Send(oMailMessage);
}
catch (Exception ex)
{
//breakpoint here to determine what the error is:
Console.WriteLine(ex.Message);
}
From here, please edit your question with that exception details.
Its hard to tell, but one possibility is that you haven't enabled anonymous access on the SMTP virtual server. Go to the the virtual server properties dialog, select the Access tab, click the Access Control button, and make sure that Anonymous Access is enabled.
There doesn't appear to be anything functionally wrong with your program. It's likely a configuration issue between your program and the mail server. I would try the following to diagnose the problem.
Wrap the code in a try/catch block and see if the exception message contains useful data
Use 127.0.0.1 instead of localhost just to rule out anything crazy
Ensure your SMTP server is running on the standard port (25 I believe)
Hello you can follow the following code:
try
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("your gmail id", "password");
MailMessage msg = new MailMessage();
msg.To.Add(textBoxTo.Text);
msg.From = new MailAddress("your gmail id");
msg.Subject = textBoxSubject.Text;
msg.Body = textBoxMsg.Text;
Attachment data = new Attachment(textBoxAttachment.Text);
msg.Attachments.Add(data);
client.Send(msg);
MessageBox.Show("Successfully Sent Message.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
have you tried 127.0.0.1 instead of Localhost?
Also have you tested that the SMTP service is working, check out this link for details.
In the virtual smtp server Add relay restrictions and connection control so that none of the outside connections are allowed