Please I have a working code which send mails correctly only when I execute the application from visual studio, but when I generate the .exe file and install it, I'm not able to recieve the email ! I think it's not problem coming from code, but maybe something else.
a PDF file generated using NReco.Generator and attached to each mail (it's not problem of access because i'm able to send the same files to Box without problem).
What can be the problem ? everything working well in Visual Studio, but not after installing !
This is the code to generate and send file :
void EnvoyerDOCAsync(string path)
{
SmtpClient MyMail = new SmtpClient(ConfigurationManager.AppSettings["server"], Convert.ToInt16(ConfigurationManager.AppSettings["port"]));
MyMsg = new MailMessage();
MyMsg.Priority = MailPriority.High;
MyMsg.From = new MailAddress(ConfigurationManager.AppSettings["mail"], "Sesrvice Mailing");
foreach (Fonction item in fonction.getFonctions())
{
MyMsg.To.Add(new MailAddress(item.FonctionMail, item.FonctionName));
}
MyMsg.Subject = "Hello";
MyMsg.Body = "Bonjour";
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.BodyEncoding = Encoding.UTF8;
MyMail.UseDefaultCredentials = false;
MyMail.Timeout = (60 * 5 * 1000);
NetworkCredential MyCredentials = new NetworkCredential(ConfigurationManager.AppSettings["sso"], ConfigurationManager.AppSettings["pass"]);
MyMail.Credentials = MyCredentials;
if (File.Exists(path))
{
if (path != null)
{
Attachment attachment = new Attachment(path, MediaTypeNames.Application.Octet);
System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(path);
disposition.ModificationDate = File.GetLastWriteTime(path);
disposition.ReadDate = File.GetLastAccessTime(path);
disposition.FileName = Path.GetFileName(path);
disposition.Size = new FileInfo(path).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
MyMsg.Attachments.Add(attachment);
MyMail.SendAsync(MyMsg, null);
MyMail.SendCompleted += MyMail_SendCompleted;
}
}
}
//Execute this after mail is sended to dispose the Msg and show validation message.<br/>
private void MyMail_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
MyMsg.Dispose();
MessageBox.Show("The mail was sended succesfully", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Thank you.
Related
I can send attachments with URLs, But, looking for support to send a file with an attachment. that too should download from url and attach with mail.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#email.com");
//to mail address
mail.To.Add(txtEmail.Text);
//Add the Attachment
mail.Attachments.Add(data);
//set the content
mail.Subject = txtSubject.Text;
mail.Body = "Kindly find the below attachments with the link, https://www.python.org/static/img/python-logo#2x.png";
//send the message
SmtpClient smtp = new SmtpClient("*****.********.net");
NetworkCredential Credentials = new NetworkCredential("mymail#email.com", "********");
smtp.Credentials = Credentials;
smtp.Send(mail);
Here I'm sending mail with URL as a file,
But I want to attach a file instead of sending a link
The sample URL was added as an image link.. But I wanted to add a pdf link..
In this case, I want to download a file and attach it with mail,
I use it mostly in my all projects it's working fine. its with base 64
First, make sure your Gmail account is turned on for sending emails.
public static async Task SendEmail(string toUser, string subject, string body
, string username, string password, string port, string smtpServer, string ccUsers = "", string base64Url = "")
{
var toAddress = new System.Net.Mail.MailAddress(toUser, toUser);
System.Net.Mail.MailMessage emessage = new System.Net.Mail.MailMessage();
emessage.To.Add(toAddress);
if (!string.IsNullOrEmpty(ccUsers))
{
string[] ccIds = ccUsers.Split(',');
foreach (string item in ccIds)
{
emessage.CC.Add(new System.Net.Mail.MailAddress(item));
}
}
emessage.Subject = subject;
emessage.From = new System.Net.Mail.MailAddress(username);
emessage.Body = body;
emessage.IsBodyHtml = true;
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
if (!string.IsNullOrEmpty(base64Url))
{
base64Url = base64Url.Replace("data:image/jpeg;base64,", "");
var imageBytes = Convert.FromBase64String(base64Url);
var stream = new MemoryStream(imageBytes);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg);
System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(stream, ct);
at.ContentDisposition.FileName = "Invoice.jpeg";
emessage.Attachments.Add(at);
}
var netCredential = new System.Net.NetworkCredential(username, password);
sc.Host = smtpServer;
sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
sc.UseDefaultCredentials = false;
sc.Credentials = netCredential;
sc.EnableSsl = true;
sc.Port = Convert.ToInt32(port);
await sc.SendMailAsync(emessage);
}
It works fine and mail directly reaches inbox instead of spam.. also can able to attach files from serverpath. Thank you everyone who wish to answer my questions..
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#gmail.com");
mail.To.Add("tomail#gmail.com");
//set the content
string filename = "Report1";
string fileurl = Server.MapPath("..");
fileurl = fileurl + #"\mailserver\pdf\generated\" + filename + ".pdf";
//mail.Attachments.Add(new Attachment(fileurl));
if (!string.IsNullOrEmpty(fileurl))
{
Attachment attachment = new Attachment(fileurl, MediaTypeNames.Application.Pdf);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(fileurl);
disposition.ModificationDate = File.GetLastWriteTime(fileurl);
disposition.ReadDate = File.GetLastAccessTime(fileurl);
disposition.FileName = Path.GetFileName(fileurl);
disposition.Size = new FileInfo(fileurl).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mail.Attachments.Add(attachment);
}
mail.Subject = "Subject Text";
mail.Body = "Body Text";
//send the message
SmtpClient smtp = new SmtpClient("smtpout.****.******server.net");
NetworkCredential Credentials = new NetworkCredential("mymail#gmail.com", "Password#123");
smtp.Credentials = Credentials;
//smtp.EnableSsl = true;
smtp.Send(mail);
Response.Write("<center><span style='color:green'><b>Mail has been send successfully!</b></span></center>");
}
catch (Exception ex)
{
//Response.Write("<center><span style='color:red'><b>"+ ex + "</b></span></center>");
Response.Write("<center><span style='color:red'><b>Failed to send a mail...Please check your mail id or Attachment missing</b></span></center>");
}
}
I encrypted an image,
Now I need to read that image, decrypt and attach it into an email.
For first step I try to put an image file and attach it into an Email,
but when i receive email, the attached image is corrupted !
I try many different ways, but without success.
(I created windows application project just for test, Eventually I need to use solution in MVC Web Application project)
private void btnSend_Click(object sender, EventArgs e)
{
var filePath = "D:\\3.jpg"; // path to none encrypted image file
var ms = new MemoryStream(File.ReadAllBytes(filePath));
// Create attachment
var attach = new Attachment(ms, new ContentType(MediaTypeNames.Image.Jpeg));
attach.ContentDisposition.FileName = "sample.jpg";
// Send Email
IMailSender mailSender = new MailSender();
var isSuccess = mailSender.Send(
"sample email title",
"sample#gmail.com",
"sample subject",
"sample body",
new Attachment[] { attach });
MessageBox.Show(isSuccess ? "Email sent successfully" : mailSender.ErrorMessage);
}
using (MailMessage Message = new MailMessage())
{
Message.From = new MailAddress("from#mail.com");
Message.Subject = "My Subject";
Message.Body = "My Body";
Message.To.Add(new MailAddress("to#mail.com"));
//Attach more file
foreach (var item in Attachment)
{
MemoryStream ms = new MemoryStream(File.ReadAllBytes(filePath));
Attachment Data = new Attachment(ms, "FileName");
ContentDisposition Disposition = Data.ContentDisposition;
Disposition.CreationDate = DateTime.UtcNow.AddHours(-5);
Disposition.ModificationDate = DateTime.UtcNow.AddHours(-5);
Disposition.ReadDate = DateTime.UtcNow.AddHours(-5);
Data.ContentType = new ContentType(MediaTypeNames.Application.Pdf);
Message.Attachments.Add(Data);
}
SmtpClient smtp = new SmtpClient("SmtpAddress", "SmtpPort");
smtp.Credentials = new NetworkCredential("SmtpUser", "SmtpPassword");
await smtp.SendMailAsync(Message);
}
I hope this helps
I created C# Console App and I can't send email with file attachment named "testfile" and has no extension.
It successfully sends, but with only the first attachment ("test.png")
How can I send this file?
Here is my code:
internal static void SendTest()
{
MailMessage mail = new MailMessage("Punter#gmail.com", "Michael378#live.com",
"Success", "Attachment email");
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com", 587);
SmtpServer.Credentials = new System.Net.NetworkCredential("Punter#gmail.com", "BrudoTass");
SmtpServer.EnableSsl = true;
string test1 = #"C:\Users\Admin\Desktop\test.png"; //Picture
string test2 = #"C:\Users\Admin\Desktop\testfile"; //File without extension
var attachment1 = new Attachment(test1);
var attachment2 = new Attachment(test2);
mail.Attachments.Add(attachment1);
mail.Attachments.Add(attachment2);
SmtpServer.Send(mail);
}
Try This way
foreach (MessageAttachment ma in msg.Attachments)
mail.Attachments.Add(BuildAttachment(ma));
private Attachment BuildAttachment(MessageAttachment ma)
{
Attachment att = null;
if (ma == null || ma.FileContent == null)
return att;
att = new Attachment(new MemoryStream(ma.FileContent), ma.FileName + ma.FileType, ma.FileType.GetMimeType());
att.ContentDisposition.CreationDate = ma.CreationDate;
att.ContentDisposition.ModificationDate = ma.ModificationDate;
att.ContentDisposition.ReadDate = ma.ReadDate;
att.ContentDisposition.FileName = ma.FileName;
att.ContentDisposition.Size = ma.FileSize;
return att;
}
I have created a method that collect every file in a folder and then inserts them into a zip file. The zip file is then sent via mail to a customer. My problem is that I can send a mail message with the zip file attached without any problems, But if another user generates the zip file and sends it, it will look like this.
I had the same issue when trying to attach excel files to a mail message. But i found out that you have to set a ContentType of the files you attach. And after adding this line: ContentType ct = new ContentType("application/vnd.ms-excel"); for the excel files it worked.
My problem is that i am trying to attach a zip file now, i am using this line: `ContentType ct = new ContentType("application/zip"); but this doesnt work. I am using DotNetZipLib-DevKit-v1.9 to add files into a zip file.
this is my code:
public void SendMailedFilesVallensbaek()
{
string[] vallensbeakFileNames = Directory.GetFiles(vallensbaekFiles);
if (vallensbeakFileNames.Count() > 0)
{
ContentType ct = new ContentType("application/zip");
string zipFile = vallensbaekFiles+#"\someZipFile.zip";
using (ZipFile zip = new ZipFile())
{
foreach (string file in vallensbeakFileNames)
{
zip.AddFile(file);
}
zip.Save(zipFile);
}
using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("ares"))
{
using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage())
{
msg.From = new MailAddress("system#mail.dk");
msg.To.Add(new MailAddress("lmy#mail.dk "));
msg.Subject = "IBM PUDO";
msg.Body = "Best Regards";
msg.Body += "<br/>";
msg.Body += "me";
msg.IsBodyHtml = true;
Attachment attachment = new Attachment(zipFile, ct);
msg.Attachments.Add(attachment);
//foreach (string file in sentFiles)
//{
// Attachment attachment = new Attachment(file, ct);
// msg.Attachments.Add(attachment);
//}
client.Send(msg);
client.Dispose();
msg.Dispose();
ct = null;
}
}
}
}
You should check the zip file is created in your local folder or not
and your local folder is able to access by ASP.NET users.
Why can't I send xls,doc and other files - it does work for jpg,txt and others.
private void BuildAndSend(string pTo,string pCC,string pSubject,string pBody)
{
// building the mail
System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("mymail#gmail.com");
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(fromAddress, toAddress);
mm.Subject = pSubject ;
mm.Body = pBody;
System.Net.Mail.MailAddress cc = new System.Net.Mail.MailAddress(pCC);
mm.CC.Add(cc);
addAttachments(mm);
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
//sending the mail
sendMail(mm);
}
private void addAttachments(System.Net.Mail.MailMessage mm)
{
string attachmentFile;
for (int i = 0; i < lstAttachments.Items.Count ; i++)
{
string fileFullName = pullDictionary[i];
attachmentFile = fileFullName;
System.Net.Mail.Attachment mailAttachment = new System.Net.Mail.Attachment(attachmentFile);
mm.Attachments.Add(mailAttachment);
}
}
private void sendMail(System.Net.Mail.MailMessage mm)
{
try
{
// loging in into sending user account
string smtpHost = "smtp.gmail.com";
string userName = "mymail#gmail.com";//sending Id
string password = "mypass";
System.Net.Mail.SmtpClient mClient = new System.Net.Mail.SmtpClient();
mClient.Port = 587;
mClient.EnableSsl = true;
mClient.UseDefaultCredentials = false;
mClient.Credentials = new NetworkCredential(userName, password);
mClient.Host = smtpHost;
mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
mClient.Send(mm);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
if you can show me another way to send these files it will be great as well
If your jpegs and text files are going I'm guessing your problem may be in your path to some of the other file types or in the size of some of these other files (just a wild guess really as the code you posted looks ok).
// this looks suspect
string fileFullName = pullDictionary[i];
attachmentFile = fileFullName;
Here is a snippet of some working code. Note that I've never set either the mm.BodyEncoding = System.Text.Encoding.UTF8; or mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; properties explicitly and have had success. (Probably just an unrelated observation...)
MailMessage m = new MailMessage(_gmailEmail, _to);
m.Subject = _emailSubject;
m.Body = _body;
for (int i = 0; i < lstAttachments.Items.Count ; i++) // your list
m.Attachments.Add(new Attachment("\path\to\file\to\attach\here"));
You mentioned that you'd like to see something different... Well, your attachment code looks fine so I thought I'd provide some code that allows you to embed images inline in your email rather than as an attachment:
// the below adds embedded images an email...
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(
_body, null, System.Net.Mime.MediaTypeNames.Text.Html);
LinkedResource pic = new LinkedResource("\path\to\file\to\embed\here", System.Net.Mime.MediaTypeNames.Image.Jpeg);
pic.ContentId = "IMAGE1"; // just make sure this is a unique string if you have > 1
avHtml.LinkedResources.Add(pic);
m.AlternateViews.Add(avHtml);
Post some specific error messages/exceptions caught and you'll get more help...