Sending Attachment from Resources - c#

Alright so pretty much I know there is a simple solution for this for the life of me though I can't find it. I want to send an attachment via mail, now I have it so that it thinks it's going to send an attachment like:
message.To.Add(recieve + "#txt.att.net");
message.From = new MailAddress(user);
message.Subject = subject;
message.Body = body;
message.Attachments.Add(new Attachment(add_photo.FileName));
client.Send(message);
You know but if add_photo(The File Dialog) is emtpy it throws and error, I tried adding a catch statement for it but the program just kinda crashes almost (not like crashes crashes but functionality wise).
Anyway, I was thinking if there is no file selected by the dialog I'll just set one myself, something really small that wouldn't even matter. So I have a picture in my resources called 'DD.png' and I would like to set it if there is no file in the dialog any ideas?
Here's what I have:
if (!string.IsNullOrEmpty(add_photo.FileName))
{
add_photo.FileName = (Path.GetFullPath(Turbo_Bomber.Properties.Resources.DD.ToString()));
}
#region Providers
if (provider == "AT&T")
{
message.To.Add(recieve + "#txt.att.net");
message.From = new MailAddress(user);
message.Subject = subject;
message.Body = body;
message.Attachments.Add(new Attachment(add_photo.FileName));
client.Send(message);
} // etc
Any ideas? Thank you guys.

Stick with your first go, with a small change:
message.To.Add(recieve + "#txt.att.net");
message.From = new MailAddress(user);
message.Subject = subject;
message.Body = body;
if (!string.IsNullOrEmpty(add_photo.FileName))
{
message.Attachments.Add(new Attachment(add_photo.FileName));
}
client.Send(message);
Now you don't need to add a 'mystery' attachment.

Related

C# and EWS How to Save Message as an Email Instead of a Draft

What I have done so far is to connect to EWS, access my inbox, create an item (email) with some info in Body, Subject, From, and To, save it to the Draft folder, and finally move it to my inbox. It works, however, I get a draft in the inbox instead of an email.
Is it possible to get the message as an email with the above scenario and how can I achieve that?
Below is my code. Any input would be very appreciated.
try {
message.Save();
}
catch(Exception e21) {;
}
message.Load(PS);
message.From = new EmailAddress("someone#abc.com");
message.ToRecipients.Add("me#abc.com");
message.Body = "This is A test take 1";
message.Subject = "Testing to send as someone else...";
// add in the attachments......
message.Update(ConflictResolutionMode.AlwaysOverwrite); // require this here why????
message.Copy(theTempFolder.Id); // get the item as a draft in my mailbox instead of an email
}
catch(Exception e99) {
Console.WriteLine("Exception fail to connect to office 365 on the cloud: " + e99.Message);
}
You need to set the MessageFlags property https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/pidtagmessageflags-canonical-property to 1 (before you call update) eg
ExtendedPropertyDefinition PR_MESSAGE_FLAGS_msgflag_read = new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer);
message.SetExtendedProperty(PR_MESSAGE_FLAGS_msgflag_read, 1);
Which will then make the message look like it was received. The other way is just import an EML like https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-import-items-by-using-ews-in-exchange
Have you tried to send it to yourself with either message.Send() or message.SendAndSaveCopy() ? see more here

Sending E-Mail in C# using mail adresses from database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to send e-mail in C# and use the mail addresses in the MySQL database. I am totally a beginner by the way. This is what i did so far :
I created a method for sending e mail:
public static void sendEmail()
{
DataClassesDataContext dc = DataContext;
var _userMail = (from u in dc.Users
select u.Email).ToString();
foreach (var item in _userMail)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("mymail#gmail.com");
mail.To.Add(_userMail);
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myusername", "mypassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
And i am calling this method in one of my forms :
try
{
AppMethod.sendEmail();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
I wanted to take all mails from User table with using the _userMail and that's why I convert it to string. What should i do ? I mean where my mistake is, i couldnt find.
I assume that Item contain your email Id then you can use below menioned code
and if you want collection of mails then your query should be
var _userMail = dc.Users.Select(p=>p.Email);
just replace
mail.To.Add(_userMail);
to
mail.To.Add(item);
if Item is Object of User then you have to tried below mentioned code
mail.To.Add(item.emailId);

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
}
}

Help! Sending HTML e-mail via C# - Windows Mobile Outlook reads it as gibberish

I have a script that sends an e-mail as both plain text and HTML, and it works fine for most e-mail readers including Outlook and Gmail. However, when reading the message on a Windows Mobile smartphone, the output is:
PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIV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oNCiAgICAgICAg PEJSPg0KICAgICAgICA8QlI+DQogICAgICAgIEt1YnkyNDI0DQogICAgICAgIDxCUj4NCiAg ICAgICAgPEJSPg0KICAgICAgICBHbyB0byANCiAgICA8L0ZPTlQ+DQogICAgPEEgSFJFRj0i aHR0cDovL3d3dy5tZWdhcG9ueS5jb20vIiBUSVRMRT0iTWVnYXBvbnkgLSBEaXNjb3ZlciB0 aGUgbmV4dCBiaWcgdGhpbmciPg0KICAgICAgICA8Rk9OVCBTSVpFPSI0IiBGQUNFPSJBcmlh bCIgQ09MT1I9IiM5OTAwMDAiPk1lZ2Fwb255LmNvbTwvRk9OVD48L0E+DQogICAgICAgIDxG T05UIFNJWkU9IjQiIEZBQ0U9IkFyaWFsIj4NCiAgICAgICAgICAgIHRvIGFjY2VzcyB5b3Vy IGFjY291bnQuDQogICAgICAgICAgICA8QlI+DQogICAgICAgICAgICA8QlI+DQogICAgICAg ICAgICBUaGFuayB5b3UgZm9yIHlvdXIgc3VwcG9ydCBvZiBNZWdhcG9ueSBhbmQgaW5kZXBl bmRlbnQgbXVzaWMhPEJSPg0KICAgICAgICAgICAgPEJSPg0KICAgICAgICAgICAgU2luY2Vy ZWx5LDxCUj4NCiAgICAgICAgICAgIDxCUj4NCiAgICAgICAgICAgIFRoZSBNZWdhcG9ueSBU ZWFtPEJSPg0KICAgICAgICAgICAgPEJSPg0KICAgICAgICAgICAgPEJSPg0KICAgICAgICA8 L0ZPTlQ+PEZPTlQgU0laRT0iMiIgRkFDRT0iQXJpYWwiPipUaGlzIGlzIGFuIGF1dG9tYXRl ZCBtZXNzYWdlLiBQbGVhc2UgZG8gbm90IHJlcGx5LjwvRk9OVD4NCjwvQk9EWT4NCjwvSFRN TD4NCg==
The correct output should be: Click here to see
The code is:
SmtpClient mC = new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]);
NetworkCredential nC = new NetworkCredential(ConfigurationManager.AppSettings["smtpUsername"], ConfigurationManager.AppSettings["smtpPassword"]);
mC.UseDefaultCredentials = false;
mC.Credentials = nC;
MailAddress mFrom = new MailAddress("noreply#megapony.com", "Megapony");
MailAddress mTo = new MailAddress(forgotpwemail.Text);
MailMessage mMsg = new MailMessage(mFrom, mTo);
mMsg.IsBodyHtml = false;
mMsg.Subject = "Your Megapony Password";
mMsg.Body = getForgotPWBodyPlain(result);
System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(getForgotPWBody(result), mimeType);
mMsg.AlternateViews.Add(alternate);
try
{
mC.Send(mMsg);
pnlpwform.Visible = false;
pnlSuccess.Visible = true;
}
catch (Exception)
{
pnlResponse.Visible = true;
}
mMsg.Dispose();
Please help!
Thanks,
Paul
I would say it's a combination of the content-type and the the image that's causing the issue. The link you provided showed a nice gif with a Megapony logo, yet the content-type is set to text only. Because of this, the bits that make up the gif is being treated as a series of text characters.
This would be a good place to start: http://www.systemnetmail.com/faq/3.1.3.aspx

Categories

Resources