Email subject problem - c#

I am using MailMessage class in my program. When the subject is too long subject will look like.
Subject:
=?utf-8?B?W0VudGVycHJpc2UgUHJpb3JpdHldIC0gQ3VzdG9tZXIgSW5jaWRlbnQgNjkxNzIgZm9yIEhhcmlkaGFyYW4gKDEzMjM5OSkgaGFyaWRoYXJhbnJAc3luY2Z1c2lvbi5jb20gOiBUZXN0aW5nIFRlc3RpbmcgVGVzdGluZyBUZXNpbmcgVGVzdGluZyBUZXN0aW5nIFRlc3RpbmcgVGVzdGluZyBUZXN0aW5nIFRlc3Rpbmcg4o"
This problem occurred in server only. while debugging i have used the same subject content in my "local" but, i got correct subject.
Program:
protected MailMessage msg;
msg.Subject = subject;
Got the same (error) subject in WebMail.IHostExchange.NET also.
What is the problem?
Update:
This is a part of my coding.
public EmailSenderThread(string emailAddresses, string ccemailaddress, string from, string subject, string body)
: base()
{
msgThread = new Thread(new ThreadStart(MailSender));
this.mailAddress = emailAddresses;
this.ccmailAddress = ccemailaddress;
msg.From = new MailAddress(from);
msg.IsBodyHtml = true;
msg.Body = body;
string[] mails = emailAddresses.Split(';');
foreach (string mail in mails)
if (!string.IsNullOrEmpty(mail))
msg.To.Add(mail);
if (ccemailaddress != string.Empty)
{
string[] ccemails = ccemailaddress.Split(';');
foreach (string ccmail in ccemails)
if (!string.IsNullOrEmpty(ccmail))
msg.CC.Add(ccmail);
}
msg.Subject = subject;
msgThread.Start();
}
I have already tried with
msg.SubjectEncoding = System.Text.Encoding.UTF8;
but i got the same error. Did you got my doubt. Please let me know if I didn't explain clearly.
1) why it is working fine in local? and why it is not working when i am hosting this into server. ?
2) What is the maximum length of the subject line?

2) What is the maximum length of the subject line?
From RFC822 about unstructured header fields:
Some field bodies in this standard are defined simply as "unstructured" (which is specified below as any US-ASCII characters, except for CR and LF) with no further restrictions. These are referred to as unstructured field bodies. Semantically, unstructured field bodies are simply to be treated as a single line of characters with no further processing (except for header "folding" and "unfolding" as described in section 2.2.3).
The subject line is an unstructured field, and therefore has no imposed length limit.

Without seeing more code, I'm going to guess an encoding problem - try specifying an encoding for your subject and body. Look at this post for sample code.

Related

Line breaks being removed from email body

I'm generating a simple email using the System.Net.Mail.MailMessage class and building the body with a StringBuilder. I'm looping through a string[] and trying to append a new line each time. The problem I'm having is that I can't seem to generate a single new line each time. I can either get two or none.
What I've tried:
foreach (var message in messages)
{
body.AppendLine(message);
}
foreach (var message in messages)
{
body.Append(message + "\n");
}
foreach (var message in messages)
{
body.Append(message + System.Environment.NewLine);
}
I've also tried with string.Format().
For each example above, I get the same result. No new line being generated.
When I try the following, however, I get the expected result. A new line with an empty line in between.
foreach (var message in messages)
{
body.AppendLine(message + System.Environment.NewLine);
}
Why is it doing this and what can I do to just get a single new line each time?
Update:
So I've found that Outlook and probably Gmail (haven't tested others) are actually removing some line breaks and not others. Does anyone know why or how they determine what to remove?
When I checked the email in Outlook, I got a tiny info message saying "Extra line breaks in this message were removed" and the option to restore them. Gmail gave no such indication (that I found) but I must assume it removed them as well.
Interestingly enough I had line breaks elsewhere in the body that worked as expected, only the ones in the loop were deemed "extra".
I have modified my code to build the email body using html.
IsBodyHtml = true
If anyone knows of a way to prevent this, or what causes certain line breaks to be removed, please let me know.
Update:
Once I knew what I was looking for, I found this post which helps to explain things and gives some alternate solutions. I did not try any of them, as I think using html is the better solution in my case.
I have just ran this through LINQPad
string[] messages = new string[]{"First line in message", "Second Line in message", "Third Line in message"};
StringBuilder sbA = new StringBuilder();
StringBuilder sbB = new StringBuilder();
StringBuilder sbC = new StringBuilder();
StringBuilder sbD = new StringBuilder();
// New line for each string
foreach (var message in messages)
{
sbA.AppendLine(message);
}
// New line for each string
foreach (var message in messages)
{
sbB.Append(message + "\n");
}
// New line for each string
foreach (var message in messages)
{
sbC.Append(message + System.Environment.NewLine);
}
//One Line
foreach (var message in messages)
{
sbD.Append(message);
}
sbA.Dump();
sbB.Dump();
sbC.Dump();
sbD.Dump();
Each one performs as expected in a StringBuilder sense.
I suspect that you need to add "</br>" at the end of each AppendLine something like this (not tested):
MailMessage mail = new MailMessage(new MailAddress("someSender#email.com"), new MailAddress("someReceiver#email.com"));
string[] messages = new string[]{"First line in message", "Second Line in message", "Third Line in message"};
StringBuilder body = new StringBuilder();
body.AppendLine("<h2>My Message<h2></br>" );
foreach (var message in messages)
{
body.AppendLine(message + "</br>");
}
mail.Body = body.ToString();
mail.Dump();
Gmail will remove explicit line breaks. This code works for me when sending to Gmail, as well as Outlook with proper line breaks intact. I am completely unable to replicate your issue without seeing what your messages[] array looks like. It may be possible that some formatting could be viewed as line breaks causing all to be stripped out? I have tampered with my example strings and I cannot get Outlook nor Gmail to strip the line breaks on me.
private void SendMessage()
{
try
{
StringBuilder body = new StringBuilder();
string[] messages = { "test with a tab in it", " test with spaces", " \r\nTab, then line break", "\n\n\n\n\n\nlots of returns...", " test spaces" };
foreach (var msg in messages)
{
body.AppendLine(msg);
//body.AppendLine(string.Empty);
}
using (MailMessage message = new MailMessage())
{
message.From = new MailAddress("you#test.com", "Your Display Name");
message.ReplyToList.Add("reply-email#test.com");
message.To.Add("to#test.com");
message.Subject = "Test Line Break Message";
message.IsBodyHtml = false;
message.Priority = MailPriority.Normal;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Body = body.ToString();
using (SmtpClient smtpClient = new SmtpClient())
{
smtpClient.Host = "127.0.0.1";
smtpClient.Send(message);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
I am going to assume somewhere in your code that builds or retrieves the messages array, something is happening to cause this issue. I would believe it to be fixable, but not without seeing how that part is coded.

How to email large files using c# windows application

I'm developing an windows application in which i need to send some files as attachment through email.
Code
public string SendMail(string mFrom,
string mPass,
string mTo,
string mSub,
string mMsg,
string mFile,
bool isDel)
{
string sql = "";
try
{
System.Net.Mail.MailAddress mailfrom = new System.Net.Mail.MailAddress(mFrom);
System.Net.Mail.MailAddress mailto = new System.Net.Mail.MailAddress(mTo);
System.Net.Mail.MailMessage newmsg = new System.Net.Mail.MailMessage(mailfrom, mailto);
newmsg.IsBodyHtml = false;
if (mFile.Length > 2
&& File.Exists(mFile))
{
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(mFile);
newmsg.Attachments.Add(att);
}
newmsg.Subject = mSub;
newmsg.Body = mMsg;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(mFrom, mPass);
smtp.EnableSsl = true;
smtp.Send(newmsg);
newmsg.Dispose();
GC.Collect();
sql = "OK";
if (isDel
&& File.Exists(mFile))
{
File.Delete(mFile);
}
}
catch (Exception ex)
{
sql = ex.Message;
}
return sql;
}
This code works fine for small files.But i need to send large files up to 1-2 GB.
For that what to do.
You cannot use e-mail to get these files across and this has nothing to do with your code.
I don't think there is ANY provider out there who will support sending files of that size let alone receiving them. Even G-Mail has a limit of 25 Mb which is quite large already.
E-Mail is not the proper channel to do this.
So the problem will not be in your code, the provider will limit the size of the attachment and just refuse them when you present them with a larger file. You will get an e-mail back at your FROM address stating that the file is too large and your e-mail did not get across.
For doing this in the simplest form probably look at FTP.
I do agree with Gerald Versluis in that email is not the proper channel for this. Even if you are using your own email server that is configurable there is probably some internal limit that prevents it from sending such big files.
I’d go with FTP for this but if you really want to continue with email I’d suggest you check following first.
Is there connection timeout property on the server? If yes then try to increase it to 3 hours or something like that.
Is there enough space on the mail server?
Is there some documentation for your email server? Are there any additional details regarding attachment size ?

creating a mailing lists to sending mass email in asp.net

I want to create a mailing list via asp.net .I've studied a lots of article about it . but all of them were the same .in those article was written that I should use this code
var list = from c in context.Emails orderby c.EmailAddress select c.EmailAddress;
MailMessage mail = new MailMessage();
foreach (var c in list)
{
try
{
mail.From = new MailAddress(txtfrom.Text);
mail.To.Add(new MailAddress(c.ToString()));
mail.Subject = txtSub.Text;
mail.IsBodyHtml = true;
mail.Body = txtBody.Text;
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
}
catch (Exception)
{
}
}
so the question is that ,is this way really useful and successful to sending lots of emails? (for example 2000 emails?)
in those articles was written that i should put delay after each period times (for example after sending 50 emails).and I wanna know how to make delay between sending emails.
I'm looking for a perfessional way to create this project
I was wondering if someone gives me open source mailing list in asp.net
I'd change the code like this
var list = from c in context.Emails orderby c.EmailAddress select c.EmailAddress;
MailMessage mail = new MailMessage();
try
{
mail.From = new MailAddress(txtfrom.Text);
foreach (var c in list)
{
mail.To.Add(new MailAddress(c.ToString()));
}
mail.Subject = txtSub.Text;
mail.IsBodyHtml = true;
mail.Body = txtBody.Text;
if (FileUpload1.HasFile)
{
mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
}
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
}
catch (Exception)
{
//exception handling
}
At least, smtp.Send() is invoked only once.
Try using multiple threads, here is an example; msdn forum sendin bulk mails
Probably, you have some time limit for running you script (i.e 30 seconds). I suggest split into 2 steps:
format e-mails you need and write them into database table (with status - "not sent")
run another script/program, select N e-mails from table, send and mark them as "sent"
wait/sleep N seconds
repeat 2nd step
This lets you to send almost unlimit number of e-mails, w/o timeout
Also - pay attention if you have some limit on sending e-mails per hour/day on your hosting!
Create work items for emails to be sent and push them to queue. Then use as many competing consumers (aka workers) as you want to send those emails.
The asp app only needs to create an XML with the info and save it.
Use a windows service with a filewatcher. This service only detect the creation of the list in XML and send it.

sending inline MHTML

I was wondering if it is possible through the .NET 2.0 MailMessage object to send an inline MHTML file that is created on the fly.
By inline I mean: It should be sent in a way that the user can see it, once he opens the email, without having to open/download the attachment.
It's a bit tricky, but yes, you can do it. In fact MailMessage class is nothing more than a wrapper above the system's CDO.Message class which can do the trick.
Also you can use AlternateView functionality, it's more simple:
MailMessage mailMessage = new MailMessage("me#me.com"
,"me#me.com"
,"test"
,"");
string ContentId = "wecandoit.jpg";
mailMessage.Body = "<img src=\"cid:" + ContentId + "\"/>";
AlternateView av = AlternateView.CreateAlternateViewFromString(mailMessage.Body
,null
,MediaTypeNames.Text.Html);
LinkedResource lr = new LinkedResource(#"d:\Personal\My Pictures\wecandoit.jpg");
lr.ContentId = ContentId;
lr.ContentType.Name = ContentId;
lr.ContentType.MediaType = "image/jpeg";
av.LinkedResources.Add(lr);
mailMessage.AlternateViews.Add(av);
SmtpClient cl = new SmtpClient();
cl.PickupDirectoryLocation = #"c:\test";
cl.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
cl.Send(mailMessage);
(jdecuyper -- thanks for the plug, as I wrote aspNetEmail).
You can do this with aspNetEmail. You can replace the entire contents of the email message with your MHT.
You can't do this with System.Net.Mail, but if you want to go the commerical route, pop me an email at dave#advancedintellect.com and I'll show you how this can be done.
If you want to go an open source route, there is probably some SMTP code on codeproject that you could modify to do this. Basically, you would inject your contents into the DATA command of the SMTP process.
One thing to note: If your MHT document has embedded scripts, flash, activeX objects or anything that may be blocked by the mail client, it probably won't render the same as what you are seeing in the browser.
Are you trying to add some images to an html email?
To accomplish this you will need to embed the images inside your email. I found a tutorial to accomplish it in a few lines of code. You can also buy the aspnetemail assembly. It has always helped me a lot to send emails with embedded images, they also have an excellent support team if anything goes wrong.
Keep in mind that embedding images makes your email heavier, but nicer :)
It is possible via CDO.Message (it is necessary add to project references COM library "Microsoft CDO for Windows 2000 Library"):
protected bool SendEmail(string emailFrom, string emailTo, string subject, string MHTmessage)
{
string smtpAddress = "smtp.email.com";
try
{
CDO.Message oMessage = new CDO.Message();
// set message
ADODB.Stream oStream = new ADODB.Stream();
oStream.Charset = "ascii";
oStream.Open();
oStream.WriteText(MHTmessage);
oMessage.DataSource.OpenObject(oStream, "_Stream");
// set configuration
ADODB.Fields oFields = oMessage.Configuration.Fields;
oFields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = CDO.CdoSendUsing.cdoSendUsingPort;
oFields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = smtpAddress;
oFields.Update();
// set other values
oMessage.MimeFormatted = true;
oMessage.Subject = subject;
oMessage.Sender = emailFrom;
oMessage.To = emailTo;
oMessage.Send();
}
catch (Exception ex)
{
// something wrong
}
}
It is possible via CDO.Message (it is necessary add to project references COM library "Microsoft CDO for Windows 2000 Library"):
protected bool SendEmail(string emailFrom, string emailTo, string subject, string MHTmessage)
{
string smtpAddress = "smtp.email.com";
try
{
CDO.Message oMessage = new CDO.Message();
// set message
ADODB.Stream oStream = new ADODB.Stream();
oStream.Charset = "ascii";
oStream.Open();
oStream.WriteText(MHTmessage);
oMessage.DataSource.OpenObject(oStream, "_Stream");
// set configuration
ADODB.Fields oFields = oMessage.Configuration.Fields;
oFields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = CDO.CdoSendUsing.cdoSendUsingPort;
oFields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = smtpAddress;
oFields.Update();
// set other values
oMessage.MimeFormatted = true;
oMessage.Subject = subject;
oMessage.Sender = emailFrom;
oMessage.To = emailTo;
oMessage.Send();
}
catch (Exception ex)
{
// something wrong
}
}

Problem while sending mail by System.Net.Mail C#

This is my mail sending code. I was getting "There is Invalid character in Mail Header" error.When i changed my Computer Name some shortest name. The problem solved. But in my domain whole computer names like "04500-ab04545.xxxdomain.gov.tr" so I need to find another solution for this problem.
So I cant give a static computer name while sending mail from c# code.
MailMessage msg = new MailMessage();
msg.Body = "axxxxxx";
msg.To.Add(new MailAddress("xxxx#xxxx.domain"));
msg.From = new MailAddress("xxxx#xxxx.domain","blab blalb");
msg.Subject = "Subject xxx";
SmtpClient server = new SmtpClient("xxxxxxxx",25);
server.Credentials = new NetworkCredential("xxxxx", "xxxxxxx");
SmtpClient server = new SmtpClient("mail.adalet.gov.tr",25);
server.Credentials = new NetworkCredential("xxx", "xxx");
server.Send(msg);
I suspect this might be an Encoding related issue.
Try using the new MailAddress("xxxx#xxxx.domain","blab blalb", Encoding.Default) constructor.
Else try Encoding.Unicode.
Update:
After some digging, this exception is thrown from:
void System.Net.BufferBuilder.Append(string,int,int);
This will happen if you have any characters above \xff in the email address. This is not suppose to happen, as the name should be encoded already, but something else is going funny I guess.
What headers are the message trying to send with?
You can easily dump with this MSDN snippet:
string[] keys = message.Headers.AllKeys;
Console.WriteLine("Headers");
foreach (string s in keys)
{
Console.WriteLine("{0}:", s);
Console.WriteLine(" {0}", message.Headers[s]);
I received this error when if this is modified to "network" --- then error got resolved. ( My understanding is - Incase of specified pickupdirectory option, the header -encoding utf-8 (base64) was giving error )
Hope it helps

Categories

Resources