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; })
Related
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);
This is a class from my code.
string to = message.Text;
string from = "noreply#zayzaycorporation.onmicrosoft.com";
MailMessage messagex = new MailMessage(from, to);
string mailbody = "Welcome!";
messagex.Subject = "Hello";
messagex.Body = mailbody;
messagex.Attachments.Add(new System.Net.Mail.Attachment("C:\\doc\\start.pdf"));
messagex.BodyEncoding = Encoding.UTF8;
messagex.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
System.Net.NetworkCredential basicCredential1 = new
System.Net.NetworkCredential("noreply#zayzaycorporation.onmicrosoft.com", "XXX");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicCredential1;
client.Send(messagex);
context.Done(string.Empty);
The class sends the email with an attachment, works good. But my problem is when it's published as a Web Service in azure because there doesn't find any folder named "doc" on "C:\\". How can it be referenced the attachment to a folder from the main solution?
Thanks.
The Attachment class can be constructed using a Stream, which can thus contain anything and come from anywhere.
So basically generate the attachment in memory and wrap it in a MemoryStream or similar.
Try this..
String path = Application.StartupPath + "\doc\test.xml";
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);
}
I've written a mail sending code for asp.net. it is working fine. I can attach files that are saved on disk. Now I want to attach a file that is on the internet. I can download the file and save it somewhere on disk and attach the file. but I don't want to save the file on disk. I just need to download the file in memory and attach it to my mail. need help to do that.
here is my code for sending email
public void SendMail(string To, string Subject, string Body)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("noreply#xyz.com", "xyz");
mail.To.Add(new MailAddress(To));
mail.Subject = Subject;
mail.Body = Body;
mail.IsBodyHtml = true;
using (SmtpClient smtpClient = new SmtpClient())
{
try
{
smtpClient.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
}
}
I want some thing like this
public void SendMail(string To, string Subject, string Body, URI onlineFileURI)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("noreply#xyz.com", "xyz");
mail.To.Add(new MailAddress(To));
mail.Subject = Subject;
mail.Body = Body;
mail.IsBodyHtml = true;
//Create the attachment from URL
var attach = [Attachemnt from URL]
mail.Attachments.Add(attach)
using (SmtpClient smtpClient = new SmtpClient())
{
try
{
smtpClient.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
}
}
How I can download the file in memory and attach it?
This is how I ended up doing it based of previous posts:
var url = "myurl.com/filename.jpg"
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse HttpWResp = (HttpWebResponse)req.GetResponse())
using (Stream responseStream = HttpWResp.GetResponseStream())
using (MemoryStream ms = new MemoryStream())
{
responseStream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
Attachment attachment = new Attachment(ms, filename, MediaTypeNames.Image.Jpeg);
message.Attachments.Add(attachment);
_smtpClient.Send(message);
}
You can do it by converting page into Stream/byte array and send it
Here is the code
string strReportUser = "RSUserName";
string strReportUserPW = "MySecretPassword";
string strReportUserDomain = "DomainName";
string sTargetURL = "http://SqlServer/ReportServer?" +
"/MyReportFolder/Report1&rs:Command=Render&rs:format=PDF&ReportParam=" +
ParamValue;
HttpWebRequest req =
(HttpWebRequest)WebRequest.Create( sTargetURL );
req.PreAuthenticate = true;
req.Credentials = new System.Net.NetworkCredential(
strReportUser,
strReportUserPW,
strReportUserDomain );
HttpWebResponse HttpWResp = (HttpWebResponse)req.GetResponse();
Stream fStream = HttpWResp.GetResponseStream();
HttpWResp.Close();
//Now turn around and send this as the response..
ReadFullyAndSend( fStream );
ReadFullyAnd send method. NB: the SendAsync call so your not waiting for the server to send the email completely before you are brining the user back out of the land of nod.
public static void ReadFullyAndSend( Stream input )
{
using ( MemoryStream ms = new MemoryStream() )
{
input.CopyTo( ms );
MailMessage message = new MailMessage("from#foo.com", "too#foo.com");
Attachment attachment = new Attachment(ms, "my attachment",, "application/vnd.ms-excel");
message.Attachments.Add(attachment);
message.Body = "This is an async test.";
SmtpClient smtp = new SmtpClient("localhost");
smtp.Credentials = new NetworkCredential("foo", "bar");
smtp.SendAsync(message, null);
}
}
courtesy:Get file to send as attachment from byte array
I'm trying to send an automated email from an application.
The main problem I'm having is that the picture doesn't display.
Secondary to that, the actual resource I'm supposed to be using is a PSD file I can only access with a URL.
The attach code is in from previous experiments, it attaches the file I select from the dialog in line 3
So can anyone tell me where I'm going wrong?
try{
OpenFileDialog diag = new OpenFileDialog();
diag.ShowDialog();
FileInfo inf = new FileInfo(diag.FileName);
string htmlBody = "<html><header><h1>TestPic</h1><br><img src=\"cid:filename\"></header></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource(#inf.FullName, MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
inline.ContentLink = new Uri("PSD_Url.com");
avHtml.LinkedResources.Add(inline);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
Attachment att = new Attachment(inf.FullName);
att.ContentDisposition.Inline = true;
mail.From = new MailAddress("from#gmail.com");
mail.To.Add("to#gmail.com");
mail.Subject = "Test Email";
mail.Body = String.Format(
"<h3>TEST Has Sent You A Mail</h3>" +
#"<img src=""cid:{0}"" />", inline.ContentId);
mail.IsBodyHtml = true;
mail.Attachments.Add(att);
mail.BodyEncoding = Encoding.Unicode;
mail.HeadersEncoding = Encoding.Unicode;
mail.SubjectEncoding = Encoding.Unicode;
SmtpClient smp = new SmtpClient("mailhost.com", 80);
smp.Credentials = new System.Net.NetworkCredential(#"from#gmail.com", #"password");
smp.DeliveryFormat = SmtpDeliveryFormat.International;
smp.Send(mail);
}
catch(SmtpException sEx)
{
throw sEx;
}
.PSD files will not render in most email clients. They are limited to .JPG, .PNG and .GIF. In your case, you might want to run your .PSD through imagemagick or some image converter to convert it first.
Besides that, make sure the image URL is absolute and hosted online and it should work.