Send directory as an attachment with email C# - c#

Is it possible to send a directory through email?
I'm using this method to send a log file to my email, but I want to send a directory which would be the save game folder of the game I'm working on in Unity.
I'm using this as a bug report, as I need to get the game save files to find bugs.
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
If it's not possible to send a directory what is the workaround to achieve that?

You may zip the complete directory contents and send the archive file as attachment.

A workaround: just zip it and send as file.

The GZip Class of .NET might just be what you want! MSDN Link
The Compression Snippet right off of there
public static void Compress(DirectoryInfo directorySelected)
{
foreach (FileInfo fileToCompress in directorySelected.GetFiles())
{
using (FileStream originalFileStream = fileToCompress.OpenRead())
{
if ((File.GetAttributes(fileToCompress.FullName) &
FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
{
using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream,
CompressionMode.Compress))
{
originalFileStream.CopyTo(compressionStream);
}
}
FileInfo info = new FileInfo(directoryPath + "\\" + fileToCompress.Name + ".gz");
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fileToCompress.Name, fileToCompress.Length.ToString(), info.Length.ToString());
}
}
}
}
You could also use the standard Zipping class from here ZipFile

Related

Send mail from outlook account using ASP.Net MVC

I have created a WebApplication which is used by my Team Members. They are accessing WebApp with a tunnel link on their PC. There is a function where Team Mates send email by clicking on button. This function is working on fine for me, but when they try using this function Outlook triggers email from my Outlook which is on my PC instead of their individual Outlook account.
Here is the code to trigger email
using (Db db = new Db())
{
Ticket newDTO = db.Tickets.Find(id);
Application app = new Application();
MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
mailItem.Subject = "Feedback: Ticket Escalated " + newDTO.CaseId + " For Customer " + newDTO.EscalatedOn;
mailItem.To = newDTO.Email;
mailItem.CC = "lead#mydomain.com";
mailItem.HTMLBody = "Hello " + newDTO.Number + "<b>Feedback:</b>" + "<br /><br />" + newDTO.HowCanWeDeEscalate;
mailItem.Importance = OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Send();
}
How can I make this code work? So the email is sent by their individual outlook email and not mine.
Try something like this (You need to configure the SMTP according to your server):
using System;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace SO.DtProblem
{
class Program
{
static async Task Main(string[] args)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("fromemail#mydomain.com");
mail.To.Add("toemail#mydomain.com");
mail.CC.Add("ccemail#mydomain.com");
mail.Subject = "test some subject";
mail.BodyEncoding = Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Body = "some body text here";
//SMTP Conbfiguration
string clientServer = "mail.mydomain.netORwhatever";
string smtpUserName = "fromemail#mydomain.com";
string smtpPassword = "somepassword";
SmtpClient client = new SmtpClient(clientServer);
client.Port = 25; // 587;
client.UseDefaultCredentials = true; //false;
client.Credentials = new System.Net.NetworkCredential(smtpUserName, smtpPassword);
client.EnableSsl = true; //false;
try
{
await client.SendMailAsync(mail);
}
catch (Exception ex)
{
//Handle it
}
finally
{
mail.Dispose();
client.Dispose();
}
}
}
}

Send email using c#

I am trying to send email using C# but I am getting below error.
Mailbox was unavailable. The server response was: Relay access denied. Please authenticate.
I am not sure why I am getting this error. Here, I am using smtp2go third party to send this email.
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#wraptite.com");
mail.To.Add("test1#gmail.com");
mail.Subject = "Test Email";
mail.Body = "Report";
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
//SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
I've tried your code and it work fine.
But in my case, to use the smtp server, from(email address of sender) must use the same domain to authenticate.(but gmail is available to this Send emails from a different address or alias)
So, If your SMTP server connect to smtp2go.com, try as below.
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#smtp2go.com");
Or if you need to use service of smtp2go, it would be better use rest API.
Here is updated by your comment when using gmail.
Gmail required secure app access. that's a reason why code is not work.
So, there is two options for this.
1. Update your gmail account security
(origin idea from here : C# - 이메일 발송방법)
Go to here and turn on "Less secure app access". after doing this your code will work.(it works)
2. Using "Google API Client Library for .NET."
I think this is not so easy, check this out, I found an answer related with this here
#region SendMail
//Mail Setting
string EmailSubject = "EmailSubject";
string EmailBody = "EmailBody";
try
{
string FromAddress = "abc#gmail.com";
string EmailList = "abc1#gmail.com";
string EmailServer = "ipofemailserver";
using (var theMessage = new MailMessage(FromAddress, EmailList))
{
// Construct the alternate body as HTML.
string body = "EmailBody";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
theMessage.AlternateViews.Add(alternate);
theMessage.Subject = EmailSubject;
theMessage.IsBodyHtml = true;
SmtpClient theSmtpServer = new SmtpClient();
theSmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
theSmtpServer.Host = EmailServer;
theSmtpServer.Send(theMessage);
}
}
catch (Exception ex)
{
string AppPath = AppDomain.CurrentDomain.BaseDirectory;
string ErrorPath = AppDomain.CurrentDomain.BaseDirectory + "File\\Error\\";
string OutFileTime = DateTime.Now.ToString("yyyyMMdd");
using (StreamWriter sw = new StreamWriter(ErrorPath + OutFileTime + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + ":");
sw.WriteLine(ex.ToString());
sw.Close();
}
}
#endregion

How to put an image file into a MemoryStream and attach it into an Email

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

Email Attachment from memory stream is coming as blank in C#

I am able to send an attachment in a mail but the attachment content is blank and size is being shown as 0 bytes.
After doing some search over the internet found that we need to reset the memory stream position to 0 in order to start from start.
I tried that as well but it seems it is not working. Can you please help?
Please find below my code snippet:
NOTE: I am able to save the workbook and Data is present in the saved workbook.
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream);
writer.Write(xlWorkbook);
writer.Flush();
memoryStream.Position = 0;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpclient");
mail.From = new MailAddress("from#gmail.com");
mail.To.Add("To#gmail.com");
mail.Subject = "Entry";
mail.Body = "Hello, PFA ";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(memoryStream,"xls");
attachment.ContentDisposition.FileName = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
mail.Attachments.Add(attachment);
SmtpServer.Port = 465;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("Username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
writer.Dispose();
I think the attachment is confusing the mail system. Microsoft's recommendation is to specify the content type as an octet. Below is a replacement for initializing the attachment. The reset of your code looks fine.
string filename = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
attachment = new System.Net.Mail.Attachment(memoryStream, filename, MediaTypeNames.Application.Octet);

Adding files into Zip and sending them via Mail issues C#

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.

Categories