I am writing a small utility to help process some MySQL tasks every night and have it email my personal email if it fails (this is a personal project, so no company smtp server or anything, emails going through public outlook accounts).
I tested about 5 times and each send was successful, but now any attempts to send email I get this exception:
Error sending test email: Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:OutboundSpamException; Failed to process message due to a permanent exception with message WASCL UserAction verdict is not None. Actual verdict is Suspend, ShowTierUpgrade. OutboundSpamException: WASCL UserAction verdict is not None. Actual verdict is Suspend, ShowTierUpgrade.[Hostname=BY2PR0101MB1461.prod.exchangelabs.com]
A bit of an oops on my part - didn't think Outlook would consider it as spam on the 6th try - is there anything I can do in Outlook to correct this?
I am using a service account I created in outlook to send these emails to my personal inbox.
The actual code in question:
class JobMailer
{
private string email_to;
private string email_from;
private string password;
private string email_smtp;
private bool use_ssl;
private int port;
public void Send(string subject, string body)
{
MailMessage mail = new MailMessage(email_from, email_to);
using (SmtpClient client = new SmtpClient
{
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = use_ssl,
Host = email_smtp,
Timeout = 100000,
Port = port,
Credentials = new NetworkCredential(email_from, password)
})
{
mail.Subject = subject;
mail.Body = body;
client.Send(mail);
}
}
public JobMailer(string emailTo, string smtp, string emailFrom, string pw, int p, bool ssl)
{
email_to = emailTo;
email_from = emailFrom;
password = pw;
email_smtp = smtp;
port = p;
use_ssl = ssl;
}
}
I resolved this by verifying the account I was trying to use. Each time you encounter this error an email is sent to the account with instructions on what you need to do to resolve the error. Typically you will need to verify against a phone number.
Got this error trying to send lots of emails to myself at Outlook.com, using SMTP.
To fix it I simply added a 5 second delay between the sends, for example:
foreach(var mail in mailToSend)
{
await smtpClient.SendMailAsync(mail);
Console.WriteLine("Sent email: " + mail);
await Task.Delay(5000);
}
If you aren't doing this just as a test, then you can contact the Outlook.com team and ask them to whitelist your IP (make sure you have SPF, rDNS, etc. setup first).
Related
I made a random Gmail account.I want that account to send to my personal Gmail account something, using C#. I found out about FluentEmail these days. This is the class:
public static class EmailSender
{
//the random account mail and password
private static string username = "blabla";
private static string password = "blabla";
static EmailSender()
{
NetworkCredential myCredentials = new NetworkCredential();
myCredentials.UserName = username;
myCredentials.Password = password;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = myCredentials,
Port = 465,
EnableSsl = true,
};
var sender = new SmtpSender(() => smtp);
Email.DefaultSender = sender;
}
public static async Task SendEmail(string body)
{
var email = await Email
.From(username)
.To("mymail")
.Subject("NEW BUG")
.Body(body)
.SendAsync();
if (email.Successful)
{
Acr.UserDialogs.UserDialogs.Instance.Alert("Your message was sent!", "Succesful", "Ok");
}
}
}
I don't know why but nothing happens when I click the send button.When I click it 2 times in a row the app crashes. I put a breakpoint at the start of the SendEmail function but I still don't know what's wrong. Maybe I set something wrong in the constructor?Thanks.
I'm not familiar with FluentEmail, but there are two points which are obviously problematic:
You check whether the mail has been sent successfully (if (email.Successful)). If it didn't, you just... do nothing. Instead, find out why the mail has not been sent and display that information instead. If your return object has a property Successful, I'm pretty sure it also has a property telling you what went wrong.
I did glimpse at the FluentEmail source code (based on your question), and it apparently uses .NET's built-in SmtpClient class. SmtpClient does not support SMTPS at port 465. The supported options are unauthenticated SMTP at port 25 or STARTTLS at port 587.
The original post was removed and I thought I would revise my latest issue. I understand completely that it has something to do with my username and password but am not sure of what else I can do. I have rest passwords multiple times, deleted and reestablished the username/email address multiple times and even dumped the .Net SmtpClient for the MailKit approach which I am now getting this error.
I am wonder if it has anything to do with me going through Bluehost for my domain and office365 subscription. With that said, as I began developing this application, I have noticed through Telnet I am still unable to establish a connection. Does anybody have any advice on how to send an email with SMTP (or anyway) through office365/outlook?
Here is my code:
Controller:
[HttpPost]
public async Task<IActionResult> SendContactEmail(ContactCardModel contact)
{
string emailSubject = $"Inquiry from {contact.name} from {contact.organization}";
await _emailSender.SendEmailAsync(contact.name, contact.email, emailSubject, contact.message);
ViewBag.ConfirmMsg = "Sent Successful";
return View("Contact");
}
Email Service:
public class SendEmailService : ISendEmail
{
private string _host;
private string _from;
private string _pwd;
public SendEmailService(IConfiguration configuration)
{
//TODO: Collect SMTP Configuration Settings
var smtpSection = configuration.GetSection("SMTP");
_host = smtpSection.GetSection("Host").Value;
_from = smtpSection.GetSection("From").Value;
_pwd = smtpSection.GetSection("Pwd").Value;
}
public async Task SendEmailAsync(string fromName, string fromEmail, string subject, string message)
{
//TODO: Build MailMessage Object
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(fromName, fromEmail));
mailMessage.To.Add(new MailboxAddress("App Admin", "tyler.crane#odin-development.com"));
mailMessage.Subject = subject;
BodyBuilder bodyBuilder = new BodyBuilder
{
HtmlBody = message
};
//TODO: Build SmtpClient Object and NetworkCredential Object
SmtpClient smtp = new SmtpClient();
smtp.ServerCertificateValidationCallback = (sender, certificate, certChainType, errors) => true;
smtp.AuthenticationMechanisms.Remove("XOAUTH2");
await smtp.ConnectAsync(_host, 587, SecureSocketOptions.StartTls).ConfigureAwait(false);
await smtp.AuthenticateAsync(new NetworkCredential(_from, _pwd)).ConfigureAwait(false);
await smtp.SendAsync(mailMessage).ConfigureAwait(false);
}
}
Interface:
public interface ISendEmail
{
Task SendEmailAsync(
string fromName,
string fromEmail,
string subject,
string message
);
}
Greatly appreciate anybody willing to help!
I finally figured out my own issue and it wasn't even in the slightest bit that difficult. More importantly, the message itself was very misleading and I am here to shed some light for those who are encountering the same issue.
SmtpClient smtp = new SmtpClient();
smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;
// The above Certificate Validation Callback has to be exactly as I show it.
// I, for some reason, had invalid options applied and can assure anyone who
// has followed any tutorial whatsoever, what they have inputted is wrong or for dummy
// testing purposes. Once you have this established, host has to be exactly as
// follows: smpt.office365.com and port 587 ONLY(25 is not longer supported).
smtp.AuthenticationMechanisms.Remove("XOAUTH2");
await smtp.ConnectAsync(_host, 587, SecureSocketOptions.StartTls).ConfigureAwait(false);
await smtp.AuthenticateAsync(new NetworkCredential(_from, _pwd)).ConfigureAwait(false);
await smtp.SendAsync(mailMessage).ConfigureAwait(false);
In no way shape or form did my error apply to the actual account itself. Although this may not directly apply to my issue where the tenant username/pass were not the issue, it may still be an issue for anyone. However, I do highly suggest you consider exactly what my code reflects above with the host and port suggestions I have made.
Thank you all who attempted to try and solve this and if anyone has any additional questions, I would be more than happy to answer them. Thanks!
i use the following code to send email :
public static bool SendEmail(string To, string ToName, string From, string FromName, string Subject, string Body, bool IsBodyHTML)
{
try
{
MailAddress FromAddr = new MailAddress(From, FromName, System.Text.Encoding.UTF8);
MailAddress ToAddr = new MailAddress(To, ToName, System.Text.Encoding.UTF8);
var smtp = new SmtpClient
{
Host = "smtp.datagts.net",
Port = 587,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
Credentials = new System.Net.NetworkCredential("MeEmail#...", "Password")
};
using (MailMessage message = new MailMessage(FromAddr, ToAddr)
{
Subject = Subject,
Body = Body,
IsBodyHtml = IsBodyHTML,
BodyEncoding = System.Text.Encoding.UTF8,
})
{
smtp.Send(message);
}
return true;
}
catch
{
return false;
}
}
It works on local and when i use my web site under my local IIS but when i upload it to my website it does not work and does not send email even any error occurs.
is there anybody out there to help me about this ?
UPDATE1 : i remove the try catch and catch an error with this message : Failure sending mail
UPDATE2 : I change my stmp server and use my Gmail account , look at this code :
public static bool SendEmail(string To, string ToName, string From, string FromName, string Subject, string Body, bool IsBodyHTML)
{
try
{
MailAddress FromAddr = new MailAddress(From, FromName, System.Text.Encoding.UTF8);
MailAddress ToAddr = new MailAddress(To, ToName, System.Text.Encoding.UTF8);
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("MeEmail#gmail.com", "Password")
};
using (MailMessage message = new MailMessage(FromAddr, ToAddr)
{
Subject = Subject,
Body = Body,
IsBodyHtml = IsBodyHTML,
BodyEncoding = System.Text.Encoding.UTF8,
})
{
smtp.Send(message);
}
return true;
}
catch
{
return false;
}
}
and now i get an error yet :(
I get the "MustIssueStartTlsFirst" error that mentioned in this link.
I am now trying to check #EdFS point and use port 25
UPDATE3: It is because i use the shared server , i just can change the port to 25 , and steel it does not work an give the same error, I am trying to get support from my server backup team
Assuming the SMTP server (smtp.datagts.net) is running fine, some items to check:
Your code seems to be using UseDefaultCredentials=true, but on the next line your are providing credentials
As mentioned in the comments check that Port 587 isn't blocked at your web host
If you are hosted on a shared server (not a dedicated machine), it's likely ASP.Net is set for medium trust. IF so, you cannot use any port for SMTP other than Port 25.
Update:
To try and get to the error. In your LOCAL (development) machine, add this to your web.config:
<system.web>
...
<securityPolicy>
<trustLevel name="Medium" />
</securityPolicy>
...
ASP.Net on your local machine runs in FULL TRUST. The above setting makes the current web site/application you are working on run in medium trust. You can remove/comment as necessary. The point of this exercise is to try and match what your web host settings are (it's obviously different if things work in your local machine then dies when published). It would be nice to just obtain the info from your web host..but until then....
Then try both Port 587 and 25.
It should fail on port 587 with a security exception (because of medium trust)
If your mail server only accepts SMTP connections on port 587, then of course, port 25 will not work either (but you should get a different error). The point being "...it still doesn't work..." in this case is that the SMTP server (smtp.datagts.net) only accepts connections on port 587
GMAIL is the same story. You cannot use Port 587 if your web host settings for ASP.Net is medium trust. I have been through this many times - it will "work" in my local machine, but as soon as I enable medium trust in my local development machine, it will fail.
You should ask your web host what their settings are for ASP.Net - if its some "custom" setting you can ask for a copy and use that in your dev box as well.
I use this class to send mails trough a gmail account:
public class GmailAccount
{
public string Username;
public string Password;
public string DisplayName;
public string Address
{
get
{
return Username + "#gmail.com";
}
}
private SmtpClient client;
public GmailAccount(string username, string password, string displayName = null)
{
Username = username;
Password = password;
DisplayName = displayName;
client = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(Address, password)
};
}
public void SendMessage(string targetAddress, string subject, string body, params string[] files)
{
MailMessage message = new MailMessage(new MailAddress(Address, DisplayName), new MailAddress(targetAddress))
{
Subject = subject,
Body = body
};
foreach (string file in files)
{
Attachment attachment = new Attachment(file);
message.Attachments.Add(attachment);
}
client.Send(message);
}
}
Here is an example of how I use it:
GmailAccount acc = new GmailAccount("zippoxer", "******", "Moshe");
acc.SendMessage("zippoxer#gmail.com", "Hello Self!", "like in the title...", "C:\\822d14ah857.r");
The last parameter in the SendMessage method is the location of an attachment I want to add.
I tried sending a mail with an attachment of 400KB, worked great (even 900KB works). But then I tried uploading an attachment of 4MB, didn't work. Tried 22MB -> didn't work too.
There should be a limit of 25MB per message in Gmail. My message's subject and body are almost empty so don't consider them as part of the message's size. Why do I have that low limit?
According to this post, it is a bug in .Net 4.0. The limit specified in the post is 3,050,417 bytes. You can try the work-around code included in the post. Hope this helps.
http://connect.microsoft.com/VisualStudio/feedback/details/544562/cannot-send-e-mails-with-large-attachments-system-net-mail-smtpclient-system-net-mail-mailmessage
It's still possible to send. Just change the attachment encoding to something other than Base64. I tried testing this and found that there is a IndexOutOfBoundsException in the Base64 encoding code. I was able to successfully send an 11MB file to myself using TransferEncoding.SevenBit.
Check and see if the SmtpClient object is going out of scope or otherwise being disposed before the send is complete and has sent the QUIT to the server.
Okay, this is a bug in .net 4.
Microsoft says it will be fixed in the next service pack.
I am using C# and .net for coding, to send bulk mails around 5000 mails at one shot using AWS(AMazon) SES(Simple Email Service) API, Everything is working fine if the number of mails sending are less than 500-600(approximately), but if it is more like 5000 it will send upto 500-600 and then it will stop sending emails. I have used datatable to store the mails list from database, assigned template body and subject, and then used for loop to send emails one by one. I need to know whether it is coding problem or for loop issue or some other thing ? Any suggestion is also helpful to me?
for (i = 0; i < dtable1.Rows.Count; i++)
{
Object a=dtable1.Rows[i]["student_emailid"];
String TO1=Convert.ToString(a);
TO1 = TO1.Trim();
if (TO1.Equals("")) {
continue;
}
const String FROM = "asit#amcsquare.com"; // Replace with your "From" address. This address must be verified.
String TO = TO1; // Replace with a "To" address. If your account is still in the
// sandbox, this address must be verified.
String SUBJECT = email_subject;
String BODY = templateBody;
// Supply your SMTP credentials below. Note that your SMTP credentials are different from your AWS credentials.
const String SMTP_USERNAME = "XXXXXXXXXXXX"; // Replace with your SMTP username.
const String SMTP_PASSWORD = "XXXXXXXXXXXXXXXXXX"; // Replace with your SMTP password.
// Amazon SES SMTP host name. This example uses the us-west-2 region.
const String HOST = "email-smtp.us-east-1.amazonaws.com";
// Port we will connect to on the Amazon SES SMTP endpoint. We are choosing port 587 because we will use
// STARTTLS to encrypt the connection.
const int PORT = 587;
// Create an SMTP client with the specified host name and port.
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
// Create a network credential with your SMTP user name and password.
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
//Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
//the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
client.EnableSsl = true;
System.Net.Mail.MailMessage message1 = new System.Net.Mail.MailMessage(FROM, TO, SUBJECT, BODY);
message1.IsBodyHtml = true;
client.Send(message1);
}
}
I don't know the exact reason why it is working now, but it's working. I changed the logic of the above code, it started working. Instead of fetching the SMTP connection each time, for sending each mail previously, this time I fetched the smtp connection only once and used it to send all the bulk mails at once and it started working.But the problem is the sending time, it is taking too much to send all the mails.Anyways I will find the solution for this also.
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
client.EnableSsl = true;
for(i=0;i<mail.Count;i++)
{
String TO = mail[i];
System.Net.Mail.MailMessage message1 = new System.Net.Mail.MailMessage(FROM, TO, SUBJECT, BODY);
message1.IsBodyHtml = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(message1);
}
client.Dispose();
}
Label1.Text = mail.Count.ToString() + " mails sent !!";
}