I am building a windows 8 desktop app. I have an email form with a textbox and a button.
XAML below.
<TextBox x:Name="email_txt"></TextBox>
<Button x:Name="email_btn" Content="Emial Me" Click="email_btn_Click"/>
How do I send a an email with an attachment to the email address entered in email_txt when email_btn is clicked.
I used the following in the c# code behind the XAML page
private async void email_btn_Click(Object sender, RoutedEventArgs e)
{
var mailto = new Uri("mailto:?to=tr#gmail.com&subject=Hello&body=Test Tocuh Email");
await Windows.System.Launcher.LaunchUriAsync(mailto);*/
}
This code just opens MS Outlook with the message type.
How do I send an email with an attachment when the button is clicked?
Consider using SmtpClient class. Note that this class by default will take smtp configurations from you application config file.
var mailMessage = new MailMessage("test#example.com", email_txt.Text, "Hello", "Test");
mailMessage.IsBodyHtml = true;
byte[] attachmentData; //get attachment data as byte array.
var attachmentStream = new MemoryStream(attachmentData);
var attachment = new Attachment(attachmentStream, "Test");
mailMessage.Attachments.Add(attachment);
var smtpClient = new SmtpClient(smtpServer);
smtpClient.Send(mailMessage);
The WinRT (Win App) platform doesn't have any built-in SMTP client. Instead you can use the share charm in order to send emails.
See Sharing content source app sample.
How to share files
How to share text
How to share HTML
I would include some code, but I'm not on my Windows 8 machine.
Related
In an ASP/C# application I'm sending an email with 3 file attached. The 3 files are the same type, same extension and more or less same size ( but none are empty ).
The email is sent correctly. If I open it using outlook, I have no problems. I can see the body, and the 3 files attached.
But here is my issue: If I send that mail to a Gmail Adress, then on Gmail I can see only 2 attachments.
And if I click on the download all attachment icon ( on the right ), it will download the 2 visible attachment + the third one but empty.
It's a really weird issue.
Also there is a 4th attachment which is an embedded image. And this image is display correctly in the mail body.
Here is the code I'm using to send the mail:
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("SMTP_IP_ADRESS", SMTP_IP_PORT);
mail.From = new MailAddress("MYEMAIL#DOMAIN.COM");
mail.To.Add("GMAIL_EMAIL");
mail.To.Add("OUTLOOK_EMAIL");
mail.Subject = "MSN "+Request.Params["nameMsn"];
Attachment imageAttachment = new
Attachment(Server.MapPath(Url.Content("~/Content/images/image.png")));
string contentID = "logoCare";
imageAttachment.ContentId = contentID;
mail.IsBodyHtml = true;
mail.Body = "<html><body>Have a good day.<br/>Best regards. <br/><br/><img width='200'
src=\"cid:"
+ contentID + "\"></body></html>";
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
var attachment = new Attachment(file.InputStream, file.FileName,
MediaTypeNames.Application.Octet);
mail.Attachments.Add(attachment);
}
mail.Attachments.Add(imageAttachment);
SmtpServer.Send(mail);
The third attachment you see empty can possibly be the CID embedded image that web based email clients (like Gmail) can't manage, meanwhile it works with desktop email clients like Outlook. Can you verify this?
Please take a look at here
So I'm trying to send an email through my relay smtp with an html body, subject and optional attachments. The sending works without exceptions however, the mail which is being sent ends up with an empty subject and no attachments which should get files from the wwwroot folder of my web application which is being hosted on the same domain as my API and console app. This console app will be called from the task scheduler. This program has my API as dependency so that it can call the ProcessQueue task. this one is being called correctly from my console application. To get data for the email the code will retreive data from the MailQueue table and then fill the mailmessage like so:
public async Task ProcessQueue(int range, bool send)
{
SmtpClient client = new SmtpClient
{
Host = "outbound.domain",
Port = 587,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("email#domain.com", "")
};
var items = await _context.MailQueues.Take(range).ToListAsync();
MailMessage message = new MailMessage();
foreach (var item in items)
{
try
{
message.From = new MailAddress(item.From);
message.Subject = item.Subject; // The subject is being filled correctly in my situation, but when the email arrives it isn't
message.IsBodyHtml = true;
message.To.Add(item.To);
message.Body = item.Content;
if (send)
{
AddAttachments(message, item.Docs);
client.Send(message);
_context.MailQueues.Remove(item);
message.To.Clear();
}
}
catch(Exception ex)
{
item.Exception = ex.ToString();
_context.Entry(item).State = System.Data.Entity.EntityState.Modified;
}
}
The attachment method:
private void AddAttachments(MailMessage message, string docs)
{
if (docs != null)
{
List<string> list = JsonConvert.DeserializeObject<List<string>>(docs);
foreach (string item2 in list)
{
Attachment item = new Attachment(HttpContext.Current.Server.MapPath("/wwwroot/documents/") + item2)
{
Name = item2
};
message.Attachments.Add(item);
}
}
}
The structure of my domain:
domain.com > webapplicatie (contains my web app and its wwwroot folder)
domain.com > webapi (contains my web api)
domain.com > mailqueuer (the location of my console application)
My goal is to send the message with optional attachments, which are located in the web app's wwwroot folder, and its subject. All the data of the MailQueue objects are filled! but still I get this problem.
Does somebody know a solution to this?
I solved this problem by putting the database and smtp logic for the MailQueue into the console application. I don't exactly know why my question isn't working but I'm open for answers and suggestions!
I have a C# app that generates emails using an HTML format (AlternateView) that contains an embedded image (jpeg).
The emails can be viewed correctly on Android, iOS, Outlook (2010) on Windows, but not on the native email client on Windows 8/8.1 Phone and Tablet (although it works find in Outlook running on the Win 8.1 tablet).
However the offending email client on the Win 8 phones/tablets can correctly see emails with embedded images sent from Outlook running on a PC.
The only thing I could find was to make sure the ContentType is set on the LinkedResource -which I do in the constructor:
LinkedResource pic1 = new LinkedResource(imgPath, MediaTypeNames.Image.Jpeg);
Code below.
Any suggestions?
string picId = "Pic1-" + Guid.NewGuid().ToString();
string htmlBody = "<html><body><h1>Test Message</h1><img src=\"cid:" + picId + "\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
// Create a LinkedResource object for each embedded image
LinkedResource pic1 = new LinkedResource(imgPath, MediaTypeNames.Image.Jpeg);
pic1.ContentId = picId;
avHtml.LinkedResources.Add(pic1);
// Add the alternate views instead of using MailMessage.Body
MailMessage m = new MailMessage();
m.AlternateViews.Add(avHtml);
// Address and send the message
m.From = new MailAddress(fromAddress, fromName);
m.To.Add(new MailAddress(toAddress));
m.Subject = subject;
SmtpClient client = new SmtpClient(AsbSmtpServer);
client.Send(m);
I'm wondering how to send meeting request to allow GMail correctly recognize it?
If you try to send iCalendar meeting request definition given bellow as an alternative view using habitual code (also given bellow) via MailMessage object to GMail it will be resulted in not recognized meeting request:
But the mail with exactly the same meeting request sent via GMail UI results in recognized meeting request! Puzzling.
Does anybody know what "magic" I'm missing?
Good to notice that Outlook correctly recognizes exactly the same meeting request sent by given code.
The code to send mail with meeting request:
class Program
{
static string From = "sender#example.com";
static string TimeFormat = "yyyyMMdd\\THHmmss\\Z";
static string To = "target#example.dom";
static void Main(string[] args)
{
string content = ReadFile("event-template.ics");
content = content.Replace("#TO#", To);
content = content.Replace("#FROM#", From);
content = content.Replace("#UID#", Guid.NewGuid().ToString().Replace("-", ""));
content = content.Replace("#CREATED-AT#", DateTime.UtcNow.AddDays(-1).ToString(TimeFormat));
content = content.Replace("#DTSTART#", DateTime.UtcNow.AddDays(1).ToString(TimeFormat));
content = content.Replace("#DTEND#", DateTime.UtcNow.AddDays(1).AddHours(1).ToString(TimeFormat));
MailMessage message = new MailMessage();
message.From = new MailAddress(From);
message.To.Add(new MailAddress(To));
message.Subject = "Meeting Request from Code!";
var iCalendarContentType = new ContentType("text/calendar; method=REQUEST");
var calendarView = AlternateView.CreateAlternateViewFromString(content, iCalendarContentType);
calendarView.TransferEncoding = TransferEncoding.SevenBit;
message.AlternateViews.Add(calendarView);
using (var smtp = new SmtpClient())
{
smtp.Send(message);
}
}
public static string ReadFile(string fileName)
{
using (StreamReader r = new StreamReader(fileName))
{
return r.ReadToEnd();
}
}
}
iCalendar template definition:
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//A//B//EN
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
ORGANIZER;CN="Organizer":mailto:#FROM#
ATTENDEE;CN="Attendee";CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=
NEEDS-ACTION;RSVP=TRUE:mailto:#TO#
DTSTART:#DTSTART#
DTEND:#DTEND#
LOCATION:Location test
TRANSP:OPAQUE
SEQUENCE:0
UID:#UID#
DTSTAMP:#CREATED-AT#
CREATED:#CREATED-AT#
LAST-MODIFIED:#CREATED-AT#
DESCRIPTION:Test description\n
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR
UPD. The source of email generated by code and received by GMail (not recognized by GMail as a meeting request): http://pastebin.com/MCU6P16Y.
The source of email composed by GMail during forwarding (recognized correclty): http://pastebin.com/zfbbj9Gg
IMPORTANT UPDATE. Just changing target from my email (<my>#gmail.com) to my colleague's one (<colleague>#gmail.com) and it starts to recognize properly! Now it definitely looks like GMail issue.
(I'm sending email from the address that differs from target, sure)
UPDATE. Found exactly the same issue in GMail support forum: Bug: Gmail fails to recognize .ics calendar invitations attached to incoming messages. The issue dated by Jun, 2011 and reported as fixed to Jul, 2011. I've created new topic there: GMail fails to recognize *.ics attachment as a meeting request.
It seems that the problem is not with GMAIL recognizing the meeting request, but with problems displaying it. I was bugged by the same problem.
It was "fixed" after I changed GMAIL display language to "English (US)" from Settings menu.
So it is definitely a bug.
If you're using c# I managed to get this working outlook web, gmail, outlook 2016.
What it appears you need to do is add an alternate view, this doesn't appear to work when you have multiple views but does work for your example above.
The alternative view below:
var ct = new ContentType("text/calendar");
if (ct.Parameters != null)
{
ct.Parameters.Add("method", "REQUEST");
ct.Parameters.Add("charSet", "utf-8");
var avCal = AlternateView.CreateAlternateViewFromString(calendarAppt.ToString(), ct);
avCal.TransferEncoding = TransferEncoding.Base64;
mail.AlternateViews.Add(avCal);
}
I have a WCF service that sends email based on user input. It was brought to my attention that, recently, a particular user's email were being delivered without any body text. If .IsBodyHtml is set to true, no body text is transferred; but, if .IsBodyHtml is set to false, the body has the appropriate text. However, it doesn't seem to be consistent, as it seems to occur only when said user's email address is set as the "From" address.Tech Details:We have an MS Exchange mail server. I'm composing a MailMessage object passing it to the built-in SMTP class to send the message.
The code has been simplified, a bit, for brevity/clarity. Nevertheless, the original code is pretty standard/straight-forward. email refers to a LINQ-to-SQL class object
MailMessage message = new MailMessage();
message.From = new MailAddress(email.fromAddress);
message.To.Add(email.toRecipient);
message.Subject = email.emailSubject;
//set email body
message.IsBodyHtml = true;
message.Body = email.emailBody;
Attachment attachmentFile = null;
if (email.hasAttachment == true)
{
//retrieve attachments for emailID
var attachments = from attach in db.EmailAttachments
where attach.emailID == emailID
select attach;
foreach (var attachment in attachments)
{//attach each attachment
string filePath = Path.Combine(UPLOAD_DIRECTORY, emailID.ToString(), attachment.fileName);
attachmentFile = new Attachment(filePath);
message.Attachments.Add(attachmentFile); //set attachment from input path
}
}
SmtpClient client = new SmtpClient(SMTP_SERVER, SMTP_PORT); //set SMTP server name/URL and port
client.Send(message); //try to send the SMTP email
Since the problem relates to a user, it is probably related to the setting of this user.
Log in as that user and open outlook
Select: File -> Options -> Mail
Scroll down to the section "Message Format"
Probably "Convert to PlainText Format is selected" change this to "Convert to HTML Format"