Send email from ASMX web service - c#

Recently somebody answered me on this site, that this method can send email from .net application:
public static void SendEmail(bool isHTML, string toEmail, string fromEmail, string subject, string message)
{
var sm = new SmtpClient("smtp.mail.ru");
sm.Credentials = new NetworkCredential("MyLogin", "MyPass");
var m = new MailMessage(fromEmail, toEmail) { Subject = subject, Body = message };
if (isHTML)
{
m.IsBodyHtml = true;
}
sm.Send(m); // SmtpException
}
It is true. But now I want to use this method from Asp.Net WebService, but I have SmtpException at last string. Why? And do I send email from web service.

So the problem is not with your code, rather the transaction with the SMTP server is failing for some reason. If you have access to the SMTP server, check its logs. Otherwise you might have to use a sniffer like WireShark to figure it out.
To verify this, you can try using a different mail server, assuming you have proper access to that server it should send the mail properly.

Related

SmtpCommandException: Incorrect authentication data Unknown location AuthenticationException: 535: Incorrect authentication data

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!

Doubts on sending more than one email asynchronously in MVC3

In my application I have a functionality to save and publish articles. So when I click on "Save and Publish" button three things happened:
Published articles get saved in database.
A Notification email goes to a group of users that a new articles is available.
After sending emails page get redirect to "Article Listing" page without showing any success or failure message for an email.
Now Number of users who will receive emails can vary say for e.g 10, 30 50 and so on. I want to send notification emails asynchronously so that page won't get block until all the mails doesn't go to their receptionists.
Given below is a piece of code from "PublishArticle" action method
foreach (string to in emailIds)
{
ArticleNotificationDelegate proc = Email.Send;
IAsyncResult asyncResult = proc.BeginInvoke(subject, body, to, from, cc, null, null, null);
}
Below I have defined a delegate to invoke Send method
private delegate bool ArticleNotificationDelegate (string subject, string body, string to, string from, string cc, string bcc = null);
and this is the code to send an email:
public static bool Send(string subject, string body, string to, string from, string cc, string bcc = null)
{
bool response;
MailMessage mail = new MailMessage();
MailAddress fromAddress = new MailAddress(from);
mail.To.Add(to);
if (!string.IsNullOrWhiteSpace(cc))
{
mail.CC.Add(cc);
}
if (!string.IsNullOrWhiteSpace(bcc))
{
mail.Bcc.Add(bcc);
}
mail.From = fromAddress;
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
try
{
client.Send(mail);
response = true;
}
catch (Exception)
{
response = false;
}
finally
{
client.Dispose();
mail.Dispose();
}
return response;
}
Although this code is working fine but still I want to know that whether my this approach is fine and will not cause any problem in future.
If there is a better approach to accomplish my objective then please suggest me.
Note: As I am using .net framework 4.0 so cannot use the new features of Asyn and await available in 4.5.
Also I had used method client.SendAsync by simply replacing the client.Send and rest of my code in above Send method was same. After this change NO mails were being send and also it did not throw any exception. So I did not go with this change.
I want to send notification emails asynchronously so that page won't get block until all the mails doesn't go to their receptionists.
That's a very dangerous approach, because ASP.NET will feel free to tear down your app domain if there are no active requests. ASP.NET doesn't know that you've queued work to its thread pool (via BeginInvoke). I recommend that you use a solution like HangFire to reliably send email.

System.Net.Mail - Trying to send a mail with attachment to gmail, works but for small attachments only

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.

Sending mail using C#

I have to send mail using C#. I follow each and every step properly, but I cannot send mail using the code below. Can anybody please help me to solve this issue? I know it's an old issue and I read all the related articles on that site about it. But I cannot solve my issue. So please help me to solve this problem. The error is: Failure sending mail. I use System.Net.Mail to do it.
using System.Net.Mail;
string mailTo = emailTextBox.Text;
string messageFrom = "riad#abc.com";
string mailSubject = subjectTextBox.Text;
string messageBody = messageRichTextBox.Text;
string smtpAddress = "mail.abc.com";
int smtpPort = 25;
string accountName = "riad#abc.com";
string accountPassword = "123";
MailMessage message = new MailMessage(messageFrom, mailTo);
message.Subject = mailSubject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.Body = messageBody;
message.BodyEncoding = System.Text.Encoding.UTF8;
SmtpClient objSmtp = new SmtpClient(smtpAddress, smtpPort);
objSmtp.UseDefaultCredentials = false;
NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(accountName, accountPassword);
objSmtp.Credentials = basicAuthenticationInfo;
objSmtp.Send(message);
MessageBox.Show("Mail send properly");
If the target mail server is an IIS SMTP (or indeed any other) server then you'll have to check the relay restrictions on that server.
Typically, you either have to configure the mail server to accept incoming relay from your machine's name (if in Active Directory) or IP address. Either that, or you can make it an Open Relay - but if it's a public mail server then that is not recommended as you'll have spammers relaying through it in no time.
You might also be able to configure the server to accept relayed messages from a particular identity - and if this is website code that'll mean that you will most likely have to configure the site to run as a domain user so that the NetworkCredentials are sent over correctly.
oh friends...i got the solution.
just i used the port 26.now the mail is sending properly.
int smtpPort = 26;
anyway thanks to Zoltan
riad.

C# - Sending Email - STOREDRV.Submission.Exception:OutboundSpamException

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).

Categories