So I've been pounding on this for a little bit now and I can't seem to figure out how to take a photo captured from a webcam and attach it to an email. Both send the email successfully with an image attached. However, when I try to open the image, it won't open.
First I tried using LightBuzz.SMTP
private async Task<SmtpResult> SendAlertEmail(List<CapturedPhoto> images)
{
using (SmtpClient client = new SmtpClient("smtp.gmail.com", 465, true, "mygmail#gmail.com", "myPassword"))
{
EmailMessage emailMessage = new EmailMessage();
emailMessage.Sender.Address = "IoTAlertApp#donotreply.com";
emailMessage.Sender.Name = "IoT App";
emailMessage.To.Add(new EmailRecipient("myemail#gmail.com"));
emailMessage.Subject = "ALERT | MOTION DETECTED";
emailMessage.Body = "This is an email sent from a UWP app!";
foreach (CapturedPhoto image in images)
{
int imageCount = 1;
string fileName = "image_" + imageCount + "_" + DateTime.Now.Ticks + ".jpg";
RandomAccessStreamReference reference = RandomAccessStreamReference.CreateFromStream(image.Frame.CloneStream());
emailMessage.Attachments.Add(new EmailAttachment(fileName, reference));
break;
}
images.Clear();
SmtpResult result = await client.SendMailAsync(emailMessage);
return result;
}
}
Then I tried using EASendMailRT and got the same result
private async Task Send_Email(byte[] image)
{
String Result = "";
try
{
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
oMail.From = new MailAddress("IoTSquatter#DoNotReply.com");
oMail.To.Add(new MailAddress("myemail#gmail.com"));
oMail.Subject = "ALERT | MOTION DETECTED";
SmtpServer oServer = new SmtpServer("smtp.gmail.com");
oServer.User = "myemail#gmail.com";
oServer.Password = "password";
oServer.Port = 465;
oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
Attachment oAttachment = oMail.AddAttachment("testImage.jpg",image);
string contentID = "test001#host";
oAttachment.ContentID = contentID;
oMail.HtmlBody = "<html><body>this is an <img src=\"cid:"
+ contentID + "\"> embedded picture.</body></html>";
await oSmtp.SendMailAsync(oServer, oMail);
Result = "Email was sent successfully!";
}
catch (Exception ep)
{
Result = String.Format("Failed to send email with the following error: {0}", ep.Message);
}
}
I'm not sure what I'm doing wrong. I think it has to do with the file format.
The answer ended up being the way I was creating the stream. Below is the proper stream to hand off to the email.
var stream = new InMemoryRandomAccessStream();
await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
Then I added it like this
string fileName = "image_"+imageCount+".png";
RandomAccessStreamReference reference = RandomAccessStreamReference.CreateFromStream(stream);
emailMessage.Attachments.Add(new EmailAttachment(fileName, reference));
Here's the result from LightBuzz
Related
So I can send up to 25MB in an email attachment. I am looking for away to check how big the file size is and if its too big break it apart and send in two emails. (Or if there is a better way to do it)?
Here is where I am sending the email with the attachment:
public static void SendEmail(List<string> recipients, MemoryStream output, string from, string subject, string htmlMessage, bool isHtml = true)
{
var host = ConfigurationManager.AppSettings["emailHost"];
var emailFrom = ConfigurationManager.AppSettings["FromEmail"];
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(from);
foreach (var r in recipients)
{
mail.To.Add(r);
}
mail.Subject = subject;
mail.IsBodyHtml = isHtml;
mail.Body = htmlMessage;
//string result = System.Text.Encoding.UTF8.GetString(output.ToArray());
SmtpClient SmtpServer = new SmtpClient(host);
SmtpServer.Port = 25;
Attachment myZip = new Attachment(output, "ClientStatements.zip");
mail.Attachments.Add(myZip);
SmtpServer.Send(mail);
}
catch (Exception ex)
{
FMBUtilities.Logger.LogErrorToSql2012PrdAndEmailTeam("DBQueries", "SendEmail", ex);
}
}
Here is where i am creating the zip file to send:
if (emails.ToString() != "")
{
var allEmails = emails[0].Split(',');
foreach (var email in allEmails)
{
if (emailValid.IsMatch(email))
{
everyEmail.Add(email);
}
else
{
return Json(new { success = false, message = $"* Not valid email address: {email}.\n\n * Please double check and try again." });
}
}
MemoryStream output = new MemoryStream();
List<string> distinctFiles = allPaths
.GroupBy(x => x.Split(new char[] { '\\' }).Last())
.Select(x => x.First())
.ToList();
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(distinctFiles, #"\");
zip.Save(output);
output.Position = 0;
DBQueries.SendEmail(everyEmail, output, fromAddress, "Client Statement Reports", "Here are your requested Client Statements", true);
}
I have found some things about setting the file size in the web.config file and things of that sort but just dont know the best way to go about this.
In a C# desktop App I send a mail to a specific user and it has an image and the end of the body as shown below
MailMessage email = new MailMessage();
email.To.Add(new MailAddress(correo));
email.From = new MailAddress("email#email.com");
email.Subject = "some text ( " + DateTime.Now.ToString("dd / MMM / yyy hh:mm:ss") + " ) ";
email.Body = "some text";
email.IsBodyHtml = true;
email.Priority = MailPriority.Normal;
string text = "some text";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(text, Encoding.UTF8, MediaTypeNames.Text.Plain);
LinkedResource LinkedImage = new LinkedResource(#"C:\Users\myUser\Documents\App\CPresentacion\Resources\comunicaciones.jpg");
LinkedImage.ContentId = "ImagenGCI";
LinkedImage.ContentType = new ContentType(MediaTypeNames.Image.Jpeg);
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
"some text <br/><img src=cid:ImagenGCI>", Encoding.UTF8,
MediaTypeNames.Text.Html);
htmlView.LinkedResources.Add(LinkedImage);
email.AlternateViews.Add(htmlView);
email.AlternateViews.Add(plainView);
SmtpClient smtp = new SmtpClient();
smtp.Host = "192.xxx.x.xxx";
smtp.Port = 25;
smtp.EnableSsl = false;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("email#email.com", "");
string output = null;
try
{
smtp.Send(email);
email.Dispose();
output = "Correo electrónico fue enviado satisfactoriamente.";
CargarDGV();
Limpiar(this);
}
catch (Exception ex)
{
output = "Error enviando correo electrónico: " + ex.Message;
}
and it works fine when I send the email from my computer but it cannot find the image when another user in another computer tries to sen the email from the App, I know the problem is in the linkedResource path but don´t know how to specify the path to work in another computer, this is my project' folders, could you please help to specify the correct path in order to work in any specific computer
With this line of code:
var path = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
You can get the directory path when your app is installed and form the proper route to your resources.
I need to send the qrcode generated from the email to his gmail account. I debugged the code and checked with html visualizer and the qrcode is displaying correctly but cannot see it in gmail message
public void generate_qrcode()
{
try
{
string imgurl;
string code = txtCode.Text;
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
imgBarCode.Height = 150;
imgBarCode.Width = 150;
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
imgurl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
//plBarCode.Controls.Add(imgBarCode);
}
SendMail(imgurl);
}
catch (Exception ex)
{
}
}
public void SendMail(String imgurl)
{
string body = "Hello ,<br /><br />Please find your QRcode below<br /><br /><img src=' " + imgurl + " ' height='100' width='100'/><br/><br/>Thanks...";
SmtpClient Smtp_Server = new SmtpClient();
MailMessage e_mail = new MailMessage();
Smtp_Server.UseDefaultCredentials = false;
Smtp_Server.Credentials = new System.Net.NetworkCredential("samplemail527#gmail.com", "Sample527");
Smtp_Server.Port = 587;
Smtp_Server.EnableSsl = true;
Smtp_Server.Host = "smtp.gmail.com";
e_mail = new MailMessage();
e_mail.From = new MailAddress("samplemail527#gmail.com");
e_mail.To.Add(txtCode.Text);
e_mail.Subject = "Email Sending";
e_mail.IsBodyHtml = true;
e_mail.Body = body;
Smtp_Server.Send(e_mail);
}
Base64 images are currently not supported by most email readers. Very unfortunate. You'll need to generate an actual image and attach it to the message with a unique id (like a GUID) and then use that ID as the image tag's src along with the CID prefix.
<img src="cid:GeneratedUniqueId" alt="Your QR Code" />
Here is the good reference to embed image in an email.
Send Email with embedded Images
Maybe you should try to use AlternateView. You have to assign an Id to a resource and use that id within HTML <img> tag. The src attribute should address this Id.Like so:
<img src="cid:ResourceId" />
Don't forget to add linked resource to alternate view.
Here is the full code I used:
Byte[] iconBytes = Convert.FromBase64String(#"iVBOR IMAGE BYTES Hy4vAAN==");
System.IO.MemoryStream iconBitmap = new System.IO.MemoryStream(iconBytes);
LinkedResource iconResource = new LinkedResource(iconBitmap, MediaTypeNames.Image.Jpeg);
iconResource.ContentId = "Icon";
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.To.Add(new MailAddress("recipient#domain.com", "Recipient Name"));
msg.From = new MailAddress("sender#domain.com", "Sender Name");
msg.Subject = "Attach image to mail";
string htmlBody = #"<html><head>";
htmlBody += #"<style>";
htmlBody += #"body{ font-family:'Calibri',sans-serif; }";
htmlBody += #"</style>";
htmlBody += #"</head><body>";
htmlBody += #"<h1>The attached image is here below</h1>";
htmlBody += #"<img src='cid:" + iconResource.ContentId + #"'/>";
htmlBody += #"</body></html>";
AlternateView alternativeView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternativeView.LinkedResources.Add(iconResource);
msg.AlternateViews.Add(alternativeView);
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Port = 25; // You can use Port 25 if 587 is blocked
client.Host = "smtp.yourhost.com";
client.Send(msg);
HELP! So i have this issue wherein theres a "noname" attachment when sending emails with pictures as seen below
Now, i want this to remove since it is not part of my emailer.
heres is my code below
public static bool SendEmailNotification(List<string> toList, List<string> ccList, string subject, string body)
{
bool isSent = true;
try
{
var mail = new MailMessage();
var smtpClient = new SmtpClient(Constants.SMTP.SMTPClient);
var alternateView = AlternateView.CreateAlternateViewFromString(body, null, Constants.SMTP.Format);
mail.From = new MailAddress(Constants.SMTP.EmailAddress);
if (toList != null && toList.Any())
{
foreach (var email in toList)
{
mail.To.Add(email);
}
if (ccList != null && ccList.Any())
{
foreach (var email in ccList)
{
mail.CC.Add(email);
}
}
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.AlternateViews.Add(alternateView);
smtpClient.Credentials = new NetworkCredential(Constants.SMTP.EmailAddress,
Constants.SMTP.EmailPassword, Constants.SMTP.Email);
smtpClient.Send(mail);
}
else
{
isSent = false;
}
}
catch
{
isSent = false;
}
return isSent;
}
The attachment is actually your image payload in binary. It's set to "noname". Reason being is certain parameters aren't set properly. In this case, to do it properly refer to https://brutaldev.com/post/sending-html-e-mail-with-embedded-images-(the-correct-way)
if( attachementFile!=null)
{
Attachment attachment = new Attachment(attachementFile, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachementFile);
disposition.ModificationDate = File.GetLastWriteTime(attachementFile);
disposition.ReadDate = File.GetLastAccessTime(attachementFile);
disposition.FileName = Path.GetFileName(attachementFile);
disposition.Size = new FileInfo(attachementFile).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
return attachment;
}
Here's the code from the link in #kendolew's answer with an example on how to properly include an attachment:
public static void SendMessageWithEmbeddedImages()
{
string htmlMessage = #"<html>
<body>
<img src='cid:EmbeddedContent_1' />
</body>
</html>";
SmtpClient client = new SmtpClient("mail.server.com");
MailMessage msg = new MailMessage("noreply#deventerprise.net",
"someone#deventerprise.net");
// Create the HTML view
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(
htmlMessage,
Encoding.UTF8,
MediaTypeNames.Text.Html);
// Create a plain text message for client that don't support HTML
AlternateView plainView = AlternateView.CreateAlternateViewFromString(
Regex.Replace(htmlMessage,
"<[^>]+?>",
string.Empty),
Encoding.UTF8,
MediaTypeNames.Text.Plain);
string mediaType = MediaTypeNames.Image.Jpeg;
LinkedResource img = new LinkedResource(#"C:\Images\MyImage.jpg", mediaType);
// Make sure you set all these values!!!
img.ContentId = "EmbeddedContent_1";
img.ContentType.MediaType = mediaType;
img.TransferEncoding = TransferEncoding.Base64;
img.ContentType.Name = img.ContentId;
img.ContentLink = new Uri("cid:" + img.ContentId);
htmlView.LinkedResources.Add(img);
//////////////////////////////////////////////////////////////
msg.AlternateViews.Add(plainView);
msg.AlternateViews.Add(htmlView);
msg.IsBodyHtml = true;
msg.Subject = "Some subject";
client.Send(msg);
}
I want to send a mail in xamarin.android.I can send as text with the code below without image but the problem occurs when i try to send with an image as logo. I mean, i can't find the path of the image.
My sending mail method is:
public static void SendMail(List<string> to, List<string> cc, string subject, string body,string mfrom)
{
string messageHeader = "Android E-Mail Testi";
MailMessage msg = new MailMessage();
msg.From = new MailAddress(mfrom);
msg.To.Add(new MailAddress(to[0]));
msg.CC.Add(new MailAddress(cc[0]));
var inlineLogo = new LinkedResource("Drawable://logo.png");//This path is not working.
inlineLogo.ContentId = Guid.NewGuid().ToString();
msg.Body = string.Format(#"<img class=""img-responsive"" src=""cid:{0}"" style=""width:25%; float:left""/>
<br/><br/><h3>" + messageHeader + #"</h3>" + body, inlineLogo.ContentId);
var view = AlternateView.CreateAlternateViewFromString(msg.Body, null, "text/html");
view.LinkedResources.Add(inlineLogo);
msg.AlternateViews.Add(view);
msg.IsBodyHtml = true;
msg.Subject = subject;
msg.SubjectEncoding = Encoding.UTF8;
SmtpClient smtpClient = new SmtpClient("xx.xxx.x.xxx");
msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
List<MemoryStream> mStreams = null;
msg.BodyEncoding = Encoding.Unicode;
smtpClient.Send(msg);
if (mStreams != null)
foreach (MemoryStream mStream in mStreams)
mStream.Close();
}
I can send mail by using this code in asp.net.Only difference is file path. I used it like that and it works for web development:
var inlineLogo = new LinkedResource(HostingEnvironment.MapPath("~/images/logo.png"));
Which method should i use for image(logo.png) path in xamarin?
var inlineLogo = new LinkedResource(???);
I don't know the real path.How can i reach the path of the image in the drawable folder of the Resources folder?
Directory is:
Maybe it will help you. I created ToolbarItem with icon from the same folder Resources/drawable in such way:
new ToolbarItem("ToolbarItemName", "iconName.png", () => { //Some action; })