I tried searching something here but nothing seems to fit my need.
I created an SSIS package that runs a report -> Attaches it to an email and send it to a bunch of people, many times (different recipients, different files).
Due to Zapier limitations I can't create a FreshDesk ticket with attachments and that is for me a must to have so I'm exploring FreshDesk API, but I'm no c# developer.
I found some examples online and now I'm trying to fit this code:
FreshSamples C-Sharp Create Ticket with attachment into my existing code, hoping to pass all my variable as ticket fields '
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
// initialize StreamReader class for text file
StreamReader streamReader = new StreamReader(Dts.Variables["User::MHTMailPath"].Value.ToString());
// Read the StreamReader To End and assign to local variable
string StreamText = streamReader.ReadToEnd();
// assign SSIS variable with value of StreamText local variable.
this.Dts.Variables["User::HTMLMail"].Value = StreamText;
// TODO: Add your code here
MailMessage email = new MailMessage();
if ((Dts.Variables["User::MHTEmail1"].Value.ToString() != null) && (Dts.Variables["User::MHTEmail1"].Value.ToString() != string.Empty))
{
email.To.Add(Dts.Variables["User::MHTEmail1"].Value.ToString());
}
if ((Dts.Variables["User::MHTEmail2"].Value.ToString() != null) && (Dts.Variables["User::MHTEmail2"].Value.ToString() != string.Empty))
{
email.To.Add(Dts.Variables["User::MHTEmail2"].Value.ToString());
}
if ((Dts.Variables["User::MHTEmail3"].Value.ToString() != null) && (Dts.Variables["User::MHTEmail3"].Value.ToString() != string.Empty))
{
email.To.Add(Dts.Variables["User::MHTEmail3"].Value.ToString());
}
if ((Dts.Variables["User::MHTEmail4"].Value.ToString() != null) && (Dts.Variables["User::MHTEmail4"].Value.ToString() != string.Empty))
{
email.To.Add(Dts.Variables["User::MHTEmail4"].Value.ToString());
}
//email.CC.Add(CCAddresses);
email.From = new MailAddress("xxx#xxx.com");
email.Subject = Dts.Variables["User::MHTCd"].Value.ToString() + " - " + Dts.Variables["User::MHTCustomerDS"].Value.ToString() + " R" + Dts.Variables["User::Period"].Value.ToString().Trim().Substring(Dts.Variables["User::Period"].Value.ToString().Trim().Length - 2, 2);
email.IsBodyHtml = true;
email.Body = Dts.Variables["User::HTMLMail"].Value.ToString();
string reportFile = Dts.Variables["User::ReportFile"].Value.ToString();
try
{
//For MHT file. Decode MHTML to HTML and embed in email body
if (Path.GetExtension(reportFile) == ".mht")
{
var decodedHtml = new StringBuilder();
using (var reader = new StreamReader(reportFile))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line != "Content-Transfer-Encoding: base64") continue;
reader.ReadLine();
while ((line = reader.ReadLine()) != String.Empty)
if (line != null)
decodedHtml.Append(
Encoding.UTF8.GetString(
Convert.FromBase64String(line)));
break;
}
}
email.Body = email.Body + Environment.NewLine + decodedHtml.ToString();
email.IsBodyHtml = true;
}
else
{
//Attach the file
Attachment attachmentFile = new Attachment(reportFile);
email.Attachments.Add(attachmentFile);
}
}
catch (Exception e)
{
Dts.Events.FireError(0, "create email message", e.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
//System.Diagnostics.Process proc = new System.Diagnostics.Process();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential("xxx#xxx.com", "xxxxxxx");
System.Diagnostics.Process proc = new System.Diagnostics.Process();
try
{
smtpClient.Send(email);
//email.Attachments.Dispose();
//File.Delete(reportFile);
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception e)
{
Dts.Events.FireError(0, "smtp emailing", e.Message, String.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
finally
{
if (email != null)
{
email.Dispose();
}
if (smtpClient != null)
{
//smtpClient.Dispose();
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
}
but I'm losing my mind trying to get my reportFile to be correctly "taken" by FreshDesk sample which expects a file on the filesystem. Moreover, I will need to attach more that one file so I was wondering if any good samaritan would point me in the right direction.
Thanks in advance
Ren
It will be okay to call email.Attachments.Add() multiple times to add multiple attachments:
The key part is :
To turn an existing file into an attachment:
Attachment attachmentFile = new Attachment(reportFile);
email.Attachments.Add(attachmentFile);
To turn a string block into an attachment:
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
{
writer.Write(reportFile);
writer.Flush();
stream.Position = 0;
email.Attachments.Add(new Attachment(stream, "myreport-xyz.txt", "text/plain"));
}
Related
I am using a StreamReader to read out the Username and Password from a .csv file (I'm just trying this out because I'm new to C#). For some reason, if I press sign in it works for the account in the first line of the file but not the second one. Anyone can help?
Register Code (Writer):
try
{
using (StreamWriter sw = new StreamWriter("C:\\GameLauncherKarakurt\\users.csv", true))
{
sw.WriteLine(tbxUsername.Text + ';' + tbxPassword.Text);
sw.Close();
}
}
catch
{
// Do nothing
}
Sign-in Code (Reader):
string username;
string password;
bool usernameCorrect = false;
bool passwordCorrect = false;
// Username
try
{
using (StreamReader sr = new StreamReader("C:\\GameLauncherKarakurt\\users.csv"))
{
username = sr.ReadLine();
string[] usernameSplit = username.Split(';');
string user = usernameSplit[0];
while (username != null)
{
if (tbxUsername.Text == user)
{
usernameCorrect = true;
break;
}
else
{
username = sr.ReadLine();
}
}
sr.Close();
}
}
catch
{
}
// Password
try
{
using (StreamReader sr = new StreamReader("C:\\GameLauncherKarakurt\\users.csv"))
{
password = sr.ReadLine();
string[] passwordSplit = password.Split(';');
string pass = passwordSplit[1];
while (password != null)
{
if (tbxPassword.Text == pass)
{
passwordCorrect = true;
break;
}
else
{
password = sr.ReadLine();
}
}
sr.Close();
}
}
catch
{
}
if (usernameCorrect == true && passwordCorrect == true)
{
pnlMenu.Visible = true;
tbxUsername.Clear();
tbxPassword.Clear();
}
You are not keeping the structure of CSV file. all couples of user and password must be separated by comma (",") and not by a new line,
Add a comma after each user and password couple.
Use Write() and not WriteLine().
private void Write()
{
try
{
using (StreamWriter sw = new StreamWriter("C:\\GameLauncherKarakurt\\users.csv", true))
{
// next time you add user and pass word you need to concatenate with ","
sw.Write(tbxUsername.Text + ';' + tbxPassword.Text + ",");
sw.Close();
}
}
catch()
{
// Do nothing
}
}
Here is one way to read the file. Use ReadToEnd() and split all the user and password couples to an array, each couple will be at a different index:
using (StreamReader sr = new StreamReader("C:\\GameLauncherKarakurt\\users.csv"))
{
var rows = sr.ReadToEnd();
string[] splitted = rows.Split(',');
}
Now you can split again each index of the array by the ";" separator,
keep in mind that there are some improvements you can do to your "matching"/authentication logic.
Once your file has been created, you can read the user and password from each line using the statement below:
using (StreamReader sr = new StreamReader(""C:\\GameLauncherKarakurt\\users.csv""))
{
while (!sr.EndOfStream)
{
strLine = sr.ReadLine();
string[] usernameSplit = strLine.Split(';');
string user = usernameSplit[0];
string password = usernameSplit[1];
}
}
public void AccessOutlook()
{
Application oOutlook;
NameSpace oNs;
MAPIFolder oFldr;
try
{
oOutlook = new Application();
oNs = oOutlook.GetNamespace("MAPI");
oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
string str = "Total Mail(s) in Inbox:" + oFldr.Items.Count;
string str2 = "Total Unread items = " + oFldr.UnReadItemCount;
foreach (var oMessage in oFldr.Items)
{
MailItem mitem = null;
try
{
if (oMessage != null)
{
mitem = (MailItem)oMessage;
String savepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\" + "Sridhar.html";
mitem.BodyFormat = OlBodyFormat.olFormatHTML;
mitem.SaveAs(savepath, OlSaveAsType.olHTML);
}
}
catch (System.Exception ex)
{
}
if (mitem != null)
{
string str3 = mitem.Subject;
}
}
}
catch (System.Exception ex)
{
}
finally
{
GC.Collect();
oFldr = null;
oNs = null;
oOutlook = null;
}
}
Here I want to convert mail item into PDF, hence in first step I'm trying to get mail item based on subject line and saving it in any outlook supported file formats. But I'm not able to do. Can anyone help with this?
Thanks in advance
I have windows service which periodically fetches data from table and creates excel file and mails it to users.After mail sending I need to delete that file. Have used following code:
public void LABInstrumentExcelGeneration(string filePath) {
try {
string connectionString = GetConnectionString(filePath);
List < LABInstruments > listLABInstrument = null;
listLABInstrument = new List < LABInstruments > ();
listLABInstrument = LABInstrumentBL.GetLABInstrumentList();
if (listLABInstrument.Count > 0) {
using(OleDbConnection conn = new OleDbConnection(connectionString)) {
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "CREATE TABLE [table2] (SrNo string,CalibrationDoneOn Date);";
cmd.ExecuteNonQuery();
foreach(LABInstruments tc1 in listLABInstrument) {
cmd.CommandText = "INSERT INTO [table2](SrNo,CalibrationDoneOn) VALUES('" + tc1.SrNo + "','" + tc1.CalibrationDoneOn + "');";
cmd.ExecuteNonQuery();
}
conn.Close();
conn.Dispose();
}
}
} catch (Exception ex) {}
}
SendMail(filePath, role);
if (File.Exists(filePath)) {
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
But it gives error File is being used by another process.
Ho can I delete file? Moreover, i've used OLEDB for file creation. Is there any other best practise for file creation? Have tried ExcelLibrary, but files created in it does not work in all versions of office so have dropped it.
Try this:
protected virtual bool IsLocked(FileInfo fileName)
{
FileStream fStream = null;
try
{
fStream = fileName.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
return true;
}
finally
{
if (fStream != null)
{
fStream.Close();
}
}
return false;
}
And then:
if (File.Exists(filePath))
{
FileInfo myfile = new FileInfo(filePath);
if(IsLocked(myfile))
{
File.Create(filePath).Close();
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
else
{
File.Delete(filePath);
eLog.WriteEntry("file deleted");
}
}
I think the problem may be that sendmail returns before it has finished using the file.
Instead of sendmail() I used this function which frees up the file for deletion:
public static void send(string subject, string body, string from, string to, List<string> attachments = null)
{
using (MailMessage message = new MailMessage(new MailAddress(from), new MailAddress(to)))
{
message.Subject = subject;
message.Body = body;
if (attachments != null && attachments.Count > 0)
{
foreach (string s in attachments)
{
if (s != null)
{
/* this code fixes the error where the attached file is
* prepended with the path of the file */
Attachment attachment = new Attachment(s, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(s);
disposition.ModificationDate = File.GetLastWriteTime(s);
disposition.ReadDate = File.GetLastAccessTime(s);
disposition.FileName = Path.GetFileName(s);
disposition.Size = new FileInfo(s).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
}
}
using (SmtpClient client = new SmtpClient())
{
client.Send(message);
}
}
}
im creating .doc file and sending mail. in pc dowloaded file from
attachment is opening properly but in mobile its not opening
properly. only html tags are displaying in smart phones.can u
tell me how to render this .doc file so that in mobile also attached
file can be displayed ?
attached file is not supporting in smartphones .only html tags are
displaying.
can anyone tell in my code how to use docX library in my code?
protected void btnMail_Click(object sender, EventArgs e)
{
DisplayProgressBar();
Response.Clear();
try
{
if (Session["Projectname"] != null && Session["Projectname"].ToString() != string.Empty)
{
string Projname = Session["Projectname"].ToString();
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
design.RenderControl(htmlWrite);
string strBuilder = stringWrite.ToString();
string strPath = Request.PhysicalApplicationPath + "\\Temp\\WeeklyReport of " + Projname + ".doc";
LblNoteMsg.Text = strPath;
//code changed to send mails
if (File.Exists(strPath))
{
var counter = 1;
strPath = strPath.Replace(".doc", " (" + counter + ").doc");
while (File.Exists(strPath))
{
strPath = strPath.Replace("(" + counter + ").doc", "(" + (counter + 1) + ").doc");
counter++;
}
}
using (var fStream = File.Create(strPath))
{
fStream.Close();
fStream.Dispose();
}
using(StreamWriter sWriter = new StreamWriter(strPath))
{
sWriter.Write(strBuilder);
sWriter.Close();
sWriter.Dispose();
Response.Clear();
}
DateTime input = DateTime.Now;
int delta = DayOfWeek.Monday - input.DayOfWeek;
DateTime dats = DateTime.Now.AddDays(delta);
//this week
DateTime monday = input.AddDays(delta);
string MonDate = monday.ToShortDateString();
DateTime sat = monday.AddDays(5);
string SatDate = sat.ToShortDateString();
StreamReader r = new StreamReader(Server.MapPath("~/WeeklyMail.txt"));
string body = r.ReadToEnd();
MailMessage Msg = new MailMessage();
string MailId = txtMailId.Text;
foreach (string ss in MailId.Split(",".ToCharArray()))
{
if (string.IsNullOrEmpty(ss) == false)
{
Msg.To.Add(new MailAddress(ss));
}
}
Msg.Bcc.Add(new MailAddress("support#sunlightit.com"));
body = body.Replace("<%MonDate%>", MonDate);
body = body.Replace("<%SatDate%>", SatDate);
Msg.Subject = "Weekly status Report of " + Projname + "," + DateTime.Now.ToShortDateString() + "";
Msg.Body = body;
Msg.IsBodyHtml = true;
Msg.Attachments.Add(new Attachment(strPath));
SmtpClient MailServer = new SmtpClient();
try
{
MailServer.Send(Msg);
string reply = (Msg.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnSuccess).ToString();
if (reply == "OnSuccess")
{
txtMailId.Text = "";
tblMail.Visible = false;
lblMsg.ForeColor = System.Drawing.Color.Green;
lblMsg.Text = "Mail has send succesfully";
}
else
{
lblMsg.ForeColor = System.Drawing.Color.Red;
lblMsg.Text = "Mail delivery unsuccessfull";
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
if (ex.InnerException != null)
{
Console.WriteLine("InnerException is: {0}", ex.InnerException);
}
}
}
else
{
Response.Redirect("~/Login.aspx");
}
}
catch (Exception)
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "clentscript", "alert('It is being used by another process.Please Try after sometime ');", true);
}
}
You did not make a proper .doc file. A .doc file is not composed of HTML. Word on your computer does know HTML so it will open the file, but likely the program you're using on the mobile devices will just treat it as a corrupted .doc file.
Instead, you should build a proper Word document. There's plenty of libraries for generating .docx Open Office XML Document (Word 2007) files. Find one that works for you needs, and use it.
Write the file on the server path and pass the link to user make the download:
Example:
http://yourapp.com/files/download/051651203210.doc
I am getting error as mentioned below:
The process cannot access file "E:\TempPDFs\Sample.pdf" because it is being used by another process
I happen to send the pdf from email and after email is sent i need to delete the Sample.pdf file. The code that i have written doesn't work
FileInfo DeleteFileInfo = new FileInfo(directoryPath + "\\" + filename + ".pdf");
if (DeleteFileInfo.Exists)
File.Delete(directoryPath + "\\" + filename + ".pdf");
here directorypath is E:\TempPDFs, filename is Sample
UPDATED:
public static void SendMail(string fromAddress, string[] toAddress, string[] ccAddress, string[] bccAddress, string subject, string messageBody, bool isBodyHtml, ArrayList attachments, string host, string username, string pwd, string port)
{
{
try
{
if (isBodyHtml && !htmlTaxExpression.IsMatch(messageBody))
isBodyHtml = false;
// Create the mail message
MailMessage objMailMsg;
objMailMsg = new MailMessage();
if (toAddress != null)
{
foreach (string toAddr in toAddress)
objMailMsg.To.Add(new MailAddress(toAddr));
}
if (ccAddress != null)
{
foreach (string ccAddr in ccAddress)
objMailMsg.CC.Add(new MailAddress(ccAddr));
}
if (bccAddress != null)
{
foreach (string bccAddr in bccAddress)
objMailMsg.Bcc.Add(new MailAddress(bccAddr));
}
if (fromAddress != null && fromAddress.Trim().Length > 0)
{
//if (fromAddress != null && fromName.trim().length > 0)
// objMailMsg.From = new MailAddress(fromAddress, fromName);
//else
objMailMsg.From = new MailAddress(fromAddress);
}
objMailMsg.BodyEncoding = Encoding.UTF8;
objMailMsg.Subject = subject;
objMailMsg.Body = messageBody;
objMailMsg.IsBodyHtml = isBodyHtml;
if (attachments != null)
{
foreach (string fileName in attachments)
{
if (fileName.Trim().Length > 0 && File.Exists(fileName))
objMailMsg.Attachments.Add(new Attachment(fileName));
}
}
//prepare to send mail via SMTP transport
SmtpClient objSMTPClient = new SmtpClient();
if (objSMTPClient.Credentials != null)
{
}
else
{
objSMTPClient.UseDefaultCredentials = false;
NetworkCredential SMTPUserInfo = new NetworkCredential(username, pwd);
objSMTPClient.Host = host;
objSMTPClient.Port = Int16.Parse(port);
//objSMTPClient.UseDefaultCredentials = false;
objSMTPClient.Credentials = SMTPUserInfo;
//objSMTPClient.EnableSsl = true;
//objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
}
//objSMTPClient.Host = stmpservername;
//objSMTPClient.Credentials
//System.Net.Configuration.MailSettingsSectionGroup mMailsettings = null;
//string mailHost = mMailsettings.Smtp.Network.Host;
try
{
objSMTPClient.Send(objMailMsg);
}
catch (SmtpException smtpEx)
{
if (smtpEx.Message.Contains("secure connection"))
{
objSMTPClient.EnableSsl = true;
objSMTPClient.Send(objMailMsg);
}
}
}
}
}
let me know if any query
Thanks!
Can we see a code that is responsible for sending a PDF file via e-mail? Your problem might be caused by not released memory stream. If you're using an Attachment class then you should do like the following:
using (Attachment data = new Attachment("document.pdf", MediaTypeNames.Application.Octet))
{
// 1. Adding attachment to the e-mail message
// 2. Sending out the e-mail message
}
The using statement will ensure that the Dispose method is called when the object gets out of the scope.
UPDATE
After calling the Send method make a call to Dispose of your mail message object:
objSMTPClient.Send(objMailMsg);
objMailMsg.Dispose();
Hope this will help you.
or better yet if the object implements IDisposable just write like this
((IDisposable)objSMTPClient).Dispose();