I have a C# application that uses SmtpClient to send emails. Emails all appear to be being delivered fine however when sending emails with attachments, periodically the attachment will be 0 bytes.
I'm using MemoryStream to write the attachment and the stream cursor is explicitly set to the start of the stream.
I'm using gmails smtp server to send the mail. The troubling part is sometimes attachments send fine and other times they have 0 bytes. I haven't been able to find any consistent pattern when testing either. I'll manually send 5 emails in secession all to the same email address all with the same attachment. Randomly only 1 or 2 of the email contain the attachment well the others are all 0 bytes.
Any guess? Here's the snippet of my code where I create and send the mail.
private void DispatchSmtpAsync(MessagePayload payload, IUnitOfWork unitOfWork)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
foreach (EmailAddress recipient in payload.To)
message.To.Add(new MailAddress(recipient.Email, recipient.Name));
foreach (EmailAddress recipient in payload.Cc)
message.CC.Add(new MailAddress(recipient.Email, recipient.Name));
foreach (EmailAddress recipient in payload.Bcc)
message.Bcc.Add(new MailAddress(recipient.Email, recipient.Name));
foreach (MyApp.Services.Email.Common.Models.Attachment attachment in payload.Content.Attachments)
{
byte[] content = Convert.FromBase64String(attachment.Content);
MemoryStream stream = new MemoryStream();
stream.Seek(0, SeekOrigin.Begin);
stream.Write(content, 0, content.Length);
message.Attachments.Add(new System.Net.Mail.Attachment(stream, attachment.Name, MimeMapping.GetMimeMapping(attachment.Name)));
}
message.From = new MailAddress(payload.From.Email, payload.From.Name);
message.Body = payload.Content.Html;
message.Subject = payload.Content.Subject;
message.IsBodyHtml = true;
client.Host = unitOfWork.SystemSettingRepository.GetValue<string>(SystemSettingName.SmtpHost);
client.Port = unitOfWork.SystemSettingRepository.GetValue<int>(SystemSettingName.SmtpPort);
client.EnableSsl = unitOfWork.SystemSettingRepository.GetValue<bool>(SystemSettingName.SmtpSsl);
client.Credentials = new NetworkCredential(unitOfWork.SystemSettingRepository.GetValue<string>(SystemSettingName.SmtpUsername),
unitOfWork.SystemSettingRepository.GetValue<string>(SystemSettingName.SmtpPassword));
client.SendAsync(message, Guid.NewGuid().ToString());
}
Related
I am using this code to send emails from my website (Taken from here https://help.1and1.com/hosting-c37630/scripts-and-programming-languages-c85099/aspnet-c39624/send-an-e-mail-using-aspnet-a604246.html)
//create the mail message
MailMessage mail = new MailMessage();
//set the FROM address
mail.From = new MailAddress(from);
//set the RECIPIENTS
mail.To.Add(to);
//enter a SUBJECT
mail.Subject = subject;
//Enter the message BODY
mail.Body = body;
//set the mail server (default should be smtp.1and1.com)
SmtpClient smtp = new SmtpClient("smtp.1and1.com");
//Enter your full e-mail address and password
smtp.Credentials = new NetworkCredential("admin#blank.com", "Password");
//send the message
smtp.Send(mail);
The emails being sent are not generating the html. So instead of a link showing up it will have the actual code for a link ect.
What am I doing wrong?
You have to add the following line:
mail.IsBodyHtml = true;
I have an .Net 4.5 application that sends an email, with an attachment. It works as expected when the email is opened on a desktop, but when opened on a mobile (iPhone in this case) the attachment shows as inline HTML not as an attachment.
When however I forward the same email from my desktop to the phone, the attachment shows up correctly on my phone so I am almost certain that it has to do with how I am specifying mime or content-type, disposition etc. but I can't see what I am doing wrong.
Here is the code - note that
att.ContentType = new System.Net.Mime.ContentType("multipart/mixed");
does create an attachment on iPhone but it is of type = mime-attachment that will not open.
I'm stumped & client awaits - any help greatly appreciated !
private void SendNotice(string body, string attachment, string email, bool pdf = false)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(ConfigurationManager.AppSettings["SMTP.SendFrom"]);
message.Subject = ConfigurationManager.AppSettings["MatchedNoticeSubject"];
message.To.Add(new MailAddress(email));
message.ReplyToList.Add(new MailAddress(ConfigurationManager.AppSettings["SMTP.ReplyTo"]));
message.Body = body;
message.IsBodyHtml = true;
Attachment att = Attachment.CreateAttachmentFromString(attachment, "SeniorInfo.html", System.Text.Encoding.ASCII, "text/html");
//specifying this creates an attachment of type "mime-attachment" that does not open
//att.ContentType = new System.Net.Mime.ContentType("multipart/mixed");
message.Attachments.Add(att);
SmtpClient server = new SmtpClient()
{
EnableSsl = (ConfigurationManager.AppSettings["SMTP.EnableSSL"].ToLower() == "true"),
Host = ConfigurationManager.AppSettings["SMTP.Server"],
Port = Convert.ToInt16(ConfigurationManager.AppSettings["SMTP.Port"]),
Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SMTP.Account"], ConfigurationManager.AppSettings["SMTP.Password"])
};
server.Send(message);
}
Solved after some trial and error fiddling.
Counter-intuitively the attachment ContentDisposition object is READONLY which lead me to believe that I couldn't meddle in it however the read object is apparently a reference to the actual Attachment.ContentDisposition since setting values on the read instance does (apparently) correct the problem. Also used the Enum for MediaTypeNames (System.Net.Mime.MediaTypeNames.Text.Html) tho I don't think that was the issue.
Email send now looks like this :
private void SendMatchNotice(string body, string attachment, string email, bool pdf = false)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(ConfigurationManager.AppSettings["SMTP.SendFrom"]);
message.Subject = ConfigurationManager.AppSettings["MatchedNoticeSubject"];
message.To.Add(new MailAddress(email));
message.ReplyToList.Add(new MailAddress(ConfigurationManager.AppSettings["SMTP.ReplyTo"]));
message.Body = body;
message.IsBodyHtml = true;
// Create the file attachment for this e-mail message.
Attachment att = Attachment.CreateAttachmentFromString(attachment, "SeniorInfo.html", System.Text.Encoding.ASCII, System.Net.Mime.MediaTypeNames.Text.Html);
System.Net.Mime.ContentDisposition disposition = att.ContentDisposition;
disposition.DispositionType = "attachment";
disposition.Inline = false;
disposition.FileName = "SeniorInfo.html";
disposition.CreationDate = DateTime.Now;
disposition.ModificationDate = DateTime.Now;
disposition.ReadDate = DateTime.Now;
message.Attachments.Add(att);
SmtpClient server = new SmtpClient()
{
EnableSsl = (ConfigurationManager.AppSettings["SMTP.EnableSSL"].ToLower() == "true"),
Host = ConfigurationManager.AppSettings["SMTP.Server"],
Port = Convert.ToInt16(ConfigurationManager.AppSettings["SMTP.Port"]),
Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SMTP.Account"], ConfigurationManager.AppSettings["SMTP.Password"])
};
server.Send(message);
}
In my web project, I am trying to programmatically send the contents of a text file that exists within the project to a default email address. Are there any simple ways of doing this in C#?
Something like:
// Read the file
string body = File.ReadAllText(#"C:\\MyPath\\file.txt");
MailMessage mail = new MailMessage("you#you.com", "them#them.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.google.com";
mail.Subject = "file";
// Set the read file as the body of the message
mail.Body = body;
// Send the email
client.Send(mail);
Let say your file is /files/file1.txt
So to read it Use :
var content = System.IO.File.ReadAllText(Server.MapPath("/files/file1.txt"));
And Send It by
MailMessage message = new MailMessage();
message.From = new MailAddress("your email address");
message.To.Add(new MailAddress("the target email address"));
message.Subject = "...";
message.Body = content;
var client = new SmtpClient();
client.Send(message);
Here you have an example:
MailMessage message = new MailMessage();
message.From = new MailAddress("from#from.be");
message.To.Add(new MailAddress("to#to.be"));
message.Subject = "Subject goes here.";
message.Body = File.ReadAllText("Path-to-file");
SmtpClient client = new SmtpClient();
client.Send(message);
You should read the mail outside of construction of the e-mail, but it's here just to show the reading of a file.
Kr,
Hi I want to send password validation to my users using c#, and I wish to protect my mail box getting spammed. How do I do that?
Been trying to this and it's not working:
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.Timeout = 10000;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential("login", "password");
MailMessage mailMsg = new MailMessage();
mailMsg.From = new MailAddress("noreply#mysite.com");
mailMsg.To.Add("user");
mailMsg.CC.Add("cc#ccServer.com");
mailMsg.Bcc.Add("bcc#bccServer.com");
mailMsg.Subject = "Subject";
mailMsg.Body = "BodyOfTheMailString";
smtpClient.Send(mailMsg);
Console.WriteLine("Mail sent");
The user i am sending this email to, getting my gmail account as the sender
This is not C#'s task, neither the body of your message: its your mailbox configuration.
If this is just for email validation, you can always create a new email like "service#domain.com" or "noreply#domain.com" for sending these verifications messages and then set this mailbox to ignore incoming messages.
Also if you try to send messages using emails that are not registered into your server, the server can deny your request.
UPDATE:
You should initially have mentioned that you are using gmail's smtp. To prevent people to send spam gmail always sets from to your emailaddress regardless of what you write in the From property.
Set the From address on the MailMessage to "noreply#mysite.com".
MailMessage mailMsg = new MailMessage();
mailMsg .From = "noreply#mysite.com";
mailMsg .To = "to#toServer.com";
mailMsg .Cc = "cc#ccServer.com"";
mailMsg .Bcc = "bcc#bccServer.com";
mailMsg .Subject = "Subject";
mailMsg .Body = "BodyOfTheMailString";
SmtpMail.Send(mailMsg );
I use this code to try and send an email. After a few seconds, it shows me an error message claiming the operation has timed out. How can I resolve this issue?
try
{
MailAddress from = new MailAddress("from#yahoo.com", "name", Encoding.UTF8);
MailAddress to = new MailAddress("to#yahoo.com");
MailMessage message = new MailMessage(from, to);
message.Subject = "Test";
message.SubjectEncoding = Encoding.UTF8;
message.Body = "Test";
message.BodyEncoding = Encoding.UTF8;
SmtpClient client = new SmtpClient();
client.Host = "smtp.mail.yahoo.com";
client.Port = 465;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("example#yahoo.com", "Password");
client.Send(message);
MessageBox.Show("sending Successfully!!!");
}
catch (SmtpException ex)
{
MessageBox.Show(ex.ToString());
}
Are you sure that you can reach smtp.mail.yahoo.com on port 465? Sounds pretty much like a network related issue. Generally when something times out, it means that it tries to connect to the server for a certain amount of time and them stops and gives you an error.
One easy way to test this is to telnet to smtp.mail.yahoo.com on port 465 and see if it times out. You can use Putty or the built in telnet-client in windows, if you have it installed.
As per my understanding, your code won't work because yahoo.com does not provide you access via SMTP. For that you need to upgrade to Yahoo! Mail Plus.
Couldn't find any sort of kb from Yahoo! on this. I got the information from a Yahoo! article on How to read Yahoo! Mail Plus using Outlook Express. The first two lines of the article are very relevant.
Do you want to read and send your Yahoo! email with Outlook Express?
If you are a Yahoo! Mail Plus user you can.
And also, the outgoing SMTP server should be
client.Host = "plus.smtp.mail.yahoo.com";
i had the same problem
you have to set the clietn.port as 25 and you have to specify your login an password in client.Credentials = new NetworkCredential(login,password)
when i did that i can send mail without problem
there is the code
{
SmtpClient client = new SmtpClient("188.125.69.59");//you can put the ip adress or the dns of smtp server (smtp.mail.yahoo.com as exemple)
// Specify the e-mail sender.
// Create a mailing address that includes a UTF8 character
// in the display name.
MailAddress from = new MailAddress("from#yahoo.fr");
// Set destinations for the e-mail message.
MailAddress to = new MailAddress("to#gmail.com");
// Specify the message content.
MailMessage message = new MailMessage(from, to);
message.Body = "This is a test e-mail message sent by an application. ";
// Include some non-ASCII characters in body and subject.
string someArrows = new string(new char[] {'\u2190', '\u2191', '\u2192', '\u2193'});
message.Body ="cc";
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "test message 1";
message.SubjectEncoding = System.Text.Encoding.UTF8;
string userState = "test message1";
MessageBox.Show("sending");
client.Port = 25;
// client.Timeout = 40000;
client.ServicePoint.MaxIdleTime = 1;
client.Credentials = new System.Net.NetworkCredential("from#yahoo.fr", "pass");
//client.SendAsync(message, userState);
client.Send(message);
MessageBox.Show("Sending message... press c to cancel mail. Press any other key to exit.");
string answer = Console.ReadLine();
// If the user canceled the send, and mail hasn't been sent yet,
// then cancel the pending operation.
// if (answer.StartsWith("c") && mailSent == false)
//{
// client.SendAsyncCancel();
//}
// Clean up.
message.Dispose();
MessageBox.Show("Goodbye.");
}
Use following setting for domain #yahoo.co.in.
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host ="smtp.mail.yahoo.co.in";
smtp.Port = 25;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}