Been researching this issue for quite a while, but have yet to find any solution.
I can send email from the website using my regular gmail account using smtp.gmail.com as my host and port 587.
My current problem is that there's no problem sending the mail. I no longer receive an error. However, the email is never sent. Anyone have any ideas?
Here's the code:
Config:
<smtp from="admin#domain.com">
<network host="smtp.gmail.com" password="password" userName="admin#domain.com" port="587"/>
</smtp>
Code:
public void Send() {
bool bDev = ConfigurationManager.AppSettings["dev"] == "true";
MailMessage oMsg = new MailMessage();
foreach (string sAddress in To) {
if (sAddress != "") oMsg.To.Add(sAddress);
}
oMsg.From = ((FromName == null) || (FromName == "")) ?
new MailAddress(From) :
new MailAddress(From, FromName);
oMsg.Subject = Subject;
oMsg.Body = Body.ToString();
oMsg.IsBodyHtml = true;
oMsg.BodyEncoding = Encoding.UTF8;
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = (new int[] { 587, 465 }).Contains(smtp.Port);
smtp.Send(oMsg);
}
I added a second To address and resumed testing. I began to receive email to both accounts. Then after removing the second address, it started working.
I ran into a new issue where my reply-to address was using the From address. So, I added additional code to set the reply address to that of the person's email address from my form.
Code
if (!string.IsNullOrEmpty(ReplyToAddress))
oMsg.ReplyTo = new MailAddress(ReplyToAddress);
However, I ran into an issue with Gmail ignoring my defined reply-to address, and using my from address. Apparently this is by design. I couldn't find any useful information on how to override this setting, so instead I did a workaround that might prove to be helpful to anyone else having this issue.
I created a generic email address with gmail (website#gmail.com) and setup a filter. Any emails coming from admin#domain.com need to be redirected to admin#domain.com.
Now, when I run my tests, all the emails are going where they are supposed to go AND the reply to field works great.
Not the best solution as it involves me remembering to setup a new account every time I run into this issue, but it's a solution that works for the time being until a better alternative comes up.
Had exactly same issue, that no error happened but also no email was sent. Google sometimes blocks your account(usually during testing). Try logging in into gmail account and see what it says.
UPD1: also check your sent folder in gmail.
UPD2: Also make sure that "From" email is the same as your gmail email address.
Related
I am having an issue with sending emails specifically to Gmail-related accounts, and I'll be darned if I know what the issue is. This is a C# ASP.NET project, by the way.
First, the following code works, as long as I am sending to any email account OTHER than a Gmail account:
var mail = new MailMessage {
Subject = "test email",
Body = "this is only a test",
Priority = MailPriority.High,
IsBodyHtml = true,
From = new MailAddress ( "<outbound email here>" )
};
var msgID = Guid.NewGuid().ToString();
var sentBy="<outbound mail domain>";
mail.Headers.Add ( "message-id", $"<{msgID}>");
mail.Headers.Add ( "msg-id", $"<{msgID}#{sentBy}>");
mail.To.Add ( new MailAddress ( "<recipient email>" ) );
var smtpClient = new SmtpClient("<email server address>") {
Port = 587,
Credentials = new NetworkCredential("<sender's email address>", "<password>"),
};
smtpClient.Send ( mail );
I have removed email addresses and network credentials, obviously.
The code works, because as long as I send email to a NON-Gmail account, it comes through just fine. But anything going to a Gmail-related account never arrives.
I added the two lines in the code above to add a message ID to the header based on what I read in several older posts here about some mail servers, like Gmail, rejecting email messages that didn't include them, but it has not fixed the issue, and I'm out of ideas. My ISP says the SPF record for the mail server is fine, so according to them that's not the issue.
Has anyone else encountered this recently, and if so, how did you fix it?
To clarify, the comments/answers I have received so far are appreciated, but as I stated in the OP, this is a problem with sending emails TO Gmail accounts. I am using my ISP's mail server to send them, and I am adding a message ID to the header to address what the log says, that the message is missing a message ID and won't be accepted. I can send emails to other non Gmail accounts just fine, and when I inspect the headers they show a message id. So I don't know why this continues to be an issue.
So the answer to this is that the issue was related to changes Google made to policies for sending emails to Gmail accounts, which might require adjustments to the SPF record on the sending SMTP server. That was the case in this situation - the hosting company was slow to respond (took them more than a week) and had to elevate the issue to their Tier 3 techs, but once the SPF record was fixed to account for Google's changes, all was resolved.
I am working in a feature where the user is able to send mail using a asp.net webApp. The idea is send mail using address saved in their membership table. With the current code bellow what i am getting are sent mails using the address testUser#gmail.com, but what i want is send mails using the email address stored in the membership table.
Thank in advance.
var email = new MailMessage(mailContent.From, mailContent.To, mailContent.Subject, mailContent.Body);
public static SendEmailResult SendEmail(MailMessage message)
{
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
var mailClient = new SmtpClient();
var log = new SendEmailResult() { Message = message };
try
{
mailClient.Send(message);
}
catch (Exception ex)
{
log.Exception = ex;
}
return log;
}
My web config
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network enableSsl="true"
defaultCredentials="false"
host="smtp.gmail.com"
port="587"
userName="testUser#gmail.com"
password="myultrasecretpassword" />
</smtp>
</mailSettings>
</system.net>
Fortunately I think it's not possible to just send an e-mail in the name of someone else (using someone else's credentials).
As #DGibbs shows, you'd need to know the credentials of the particular user. But you don't have the password.
The SMTP protocol alone wouldn't prevent you to use any kind of sender e-mail address in the "From" field, but the .NET SmtpClient will throw an exception (SmtpException http://msdn.microsoft.com/en-us/library/swas0fwc.aspx).
The SmtpClient actually will only willing to send the e-mail if the running software's (or provided by NetworkCredentials) credentials match the from address's user.
If you use UseDefaultCredentials, the credentials (of the default) should still match the e-mail address's user and should be authorized.
What you can do is to setup a mail account for the purpose of automated mail. Even in this case there's a good chance that the software will run in the name of some other user, so system administrator has to configure that automated mail account in the mail server so that it would willing to let the software's user to send in the name of the automated account. The automated mail's subject or body can reference the user's name and e-mail if you like.
All of this is because today there are lot of mechanisms exist to prevent spamming. The system prevents you even from yourself to do anything which wouldn't be a good idea. Sending an e-mail in whoever's name is not a good idea from security point of view, even if the business requirements would require it.
System.Net.Mail provides a very clean and nice interface and API, but you have to work around the usage what you want. I've been there, done that. I mean the same situation.
Once you have the users details from the Membership table (it's up to you to do this) you can specify some credentials for the SMTP client before sending:
var mailClient = new SmtpClient();
mailClient.Credentials = new System.Net.NetworkCredential("username", "password");
//etc...
I have an service that needs to send out automated emails on failures. I feel like i have it set up but i keep on receiving the following error:
Service not available, closing transmission channel. The server response
was: 4.3.2 Service not available
I cant quite figure out where i went wrong, but here is my code:
public static void AutoEmail()
{
try
{
SmtpClient newClient = new SmtpClient();
newClient.Host = "host name";
newClient.Port = Port number;
newClient.Credentials = new System.Net.NetworkCredential(
"username", "password");
MailMessage mail = new MailMessage();
mail.To.Add(new MailAddress("something#email.com"));
mail.Body = "This is a test message.";
mail.Subject = "Test - " + DateTime.Now;
mail.From = new MailAddress("something2#email.com");
newClient.Send(mail);
}
catch (Exception ex)
{
Log.WriteException("Error in Email", ex);
}
}
Any help would be much appreciated. Thanks!
Are you sure SMTP server you are using permits applications to send emails? I had met with similar issue and root cause was Exchange server was rejecting the send request due to insufficient permissions. And I have the same steps in my code as in yours. Check for permissions.
Have you tried
newClient .UseDefaultCredentials = true;
Does it help ?
The SMTP server name only works on a computer within the network that contains that SMTP server.
You need to make sure SMTP server's host name and port number in your program is correct. All the other code in your program seem fine.
I experienced the same error before. At the end, I changed to the correct host name and port number and everything works.
For example, Outlook.com Or Hotmail email accounts
host="smtp-mail.outlook.com" port="25" enableSsl="true"
https://www.outlook-apps.com/outlook-com-pop-settings/
i have few question about smtp
im using this code to send mails if the host is gmail then it act diffrente:
foreach (string host in hosts)
{
SmtpClient sc = null;
try
{
if (emailDomain.ToLower() == "gmail.com")
{
MailSend.MailSendApp.EventLog.WriteEntry("mail to gmail.com");
sc = new SmtpClient("smtp.gmail.com", 587);
sc.UseDefaultCredentials = false;
sc.DeliveryMethod = SmtpDeliveryMethod.Network;
sc.Credentials = new NetworkCredential("UID#gmail.com", "PWD");
sc.EnableSsl = true;
} }
else
{
sc = new SmtpClient(host);
sc.Send(mailMessage);
break;
}
is it possiable to get answer from smtp :
1. that the email arrived
2. if the mail exists
thanks
If you want to receive a notification that the email has arrived you need to send the email with delivery notification options.
mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
If the email doesn't exists, you will get an email back to your sender address and not to your SMTP class.
In short, there's no easy way to determine these two thing purely from the SMTP class perspective.
Back in the day you could directly query whether the email address exists on a given server (VRFY user SMTP command). Then, SPAM was born and pretty much all email servers removed that capability because spammers would use bots to query possible email recipients on each mail server to build SPAM lists.
You will still get an ordinary bounce report (email back to the reply-to address indicating that delivery failed). I use a tool called Boogie Tools to automate processing of bounce messages.
Gmail does not offer delivery or read receipts (though some email servers still optionally allow it) for similar reasons... too much abuse potential.
I have a small email application that lets a user build a message from checkboxes and then send the message as an email. I am trying to add an image to the email, i.e. a logo or signature. The application worked fine but as I was reseaching getting the images into the email, I found that I should be using System.Net.Mail instead of Interop. So I changed my email class to the code below. Now I'm not recieving the emails. I'm assumeing this is because the code is set-up for a server and I just want to run this on my local machine. This is just something I'm playing with to help me understand some concepts so real world use is not going to be a factor. I just want to be able to test my little program on my Outlook email account locally. My code is as follows...
using System;
using System.Net.Mail;
using System.Net.Mime;
namespace Email_Notifier
{
public class EmailSender:Notification
{
string emailRecipient = System.Configuration.ConfigurationManager.AppSettings ["emailRecipient"];
public void SendMail(string message)
{
try
{
string strMailContent = message;
string fromAddress = "MyApp#gmail.com";
string toAddress = emailRecipient;
string contentId = "image1";
string path = (#"C:Libraries/Pictures/Logo.gif");
MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
mailMessage.Subject = "Email Notification";
LinkedResource logo = new LinkedResource( path , MediaTypeNames.Image.Gif);
logo.ContentId = "Logo";
// HTML formatting for logo
AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><img src=cid:Logo/><br></body></html>" + strMailContent, null, MediaTypeNames.Text.Html);
av1.LinkedResources.Add(logo);
mailMessage.AlternateViews.Add(av1);
mailMessage.IsBodyHtml = true;
SmtpClient mailSender = new SmtpClient("localhost");
mailSender.Send(mailMessage);
}
catch (Exception e)
{
Console.WriteLine("Problem with email execution. Exception caught: ", e);
}
return;
}
}
}
You specify mailSender = new SmtpClient("localhost");.
Have you set up an SMTP server on your local machine? If not, you will need to do so to use SmtpClient. Otherwise, specify a hostname other than localhost, perhaps using your Gmail account as specified here, bearing in mind you will need to configure it for authentication and SSL.
See also the documentation for SmtpClient.
There are also one or two other issues I can see with your code - but let's deal with these after getting simple mail sending working.
if your problem is that you don't have a smtp server you are talking to on your machine, you will see an exception rather than just silently not having your email delivered (which i believe is what you are seeing given that you did not list an exception, but not completely sure). it could be that you are successfully delivering to your local smtp server, but it is failing to send the mail on. if you have the iis smtp server installed and that is what you are trying to use to send the mail, you can see failed email messages in the subdirectories of C:\Inetpub\mailroot. there is a badmail subdirectory that should have failed deliveries.
if you are on windows 7, it doesn't support the iis smtp server. an alternative for having an smtp server on your machine that doesn't actually deliver the email but does show you everything that has come through for any email address is http://smtp4dev.codeplex.com/. even if i do have the iis smtp server available in my operating system, i prefer this for development needs.