I use outlook Redemption dll for creating outlook message template with c# language.
Below is my code:
RedemptionLoader.DllLocation64Bit = Server.MapPath("~/bin/dlls/Redemption64.dll");
RedemptionLoader.DllLocation32Bit = Server.MapPath("~/bin/dlls/Redemption.dll");
Interop.Redemption.RDOSession session = RedemptionLoader.new_RDOSession();
var msg = session.GetMessageFromMsgFile(templatePath);
msg.Subject = String.Format("Report");
String ImageString = Server.MapPath("~\\FolderName") + "\\" + ImageName;
RDOAttachment Attach = msg.Attachments.Add(ImageString);
Attach.ContentID = "image1";
String htb = "<html><head><title>The Title</title></head><body><h1>This is some text</h1>Image 1<br /><img src=cid:image1><br /></body></html>";
msg.HTMLBody = htb;
msg.Save();
msg.SaveAs(newPath);
Everything work and image is saved to new location. But when i check that message template, i could not see Image anywhere. instead of image it gives me error.
Update
Instead of embedded image , I tried just to attach this file. But when I open file I didn't see any attachment. I check Total Attachments with OutlookSpy, It shows me 0 attachment. Does my code wrong for attachment?
I found solution for this. I need to call session two time. First time to save attachment to my template file and than again to create new instance of it. Below is my code:
RedemptionLoader.DllLocation64Bit = Server.MapPath("~/bin/dlls/Redemption64.dll");
RedemptionLoader.DllLocation32Bit = Server.MapPath("~/bin/dlls/Redemption.dll");
Interop.Redemption.RDOSession session1 = RedemptionLoader.new_RDOSession();
var msg1 = session1.GetMessageFromMsgFile(templatePath);
msg1.Subject = String.Format("Report");
String ImageString = Server.MapPath("~\\FolderName") + "\\" + ImageName;
RDOAttachment Attach = msg1.Attachments.Add(ImageString);
Attach.ContentID = "image1";
String htb = "<html><head><title>The Title</title></head><body><h1>This is some text</h1>Image 1<br /><img src=cid:image1><br /></body></html>";
msg1.HTMLBody = htb;
msg1.Save();
Interop.Redemption.RDOSession session = RedemptionLoader.new_RDOSession();
var msg = session.GetMessageFromMsgFile(templatePath);
msg.SaveAs(newPath);
This works for me.
Related
What is wrong with my below code. I am trying to place an inline image to an email.
public string SendEmail(SendEmail emailDetails)
{
var x =
"iVBORw0KGgoAAAANSUhEUgAAAMgA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L7WfXSGpV/9DcKldzqOBkeFSzJPclLsJLcz6qX1qj8a5B3RVUwbYDEyVArL8ESThqjvBRP4pI1Kv8apAaR2fwSowO2CfwvP1SDJNW8wxJhz9pw5SU1JuVVXsmcyRqVfy9IL8imGdYB2wTeC5KUbYwlm+esDVdeUuNYKY9QXo44jkzWqPx7QXpBxpP5TYQO2CbwXpCkbGMs2TxnbbjykhrHSnmE8nLEcWSyRuXfC9ILMp7MXpBNGv2oH9KNIkUnN53kOyJG9RItklhpLeiCpJOeEU+bJNxlKATnzDGql2iRxEprVoPs8MSSoUg3cjVecqiTWGkdapAaZNNMJYc6ibWpmAc/VIPUIJtmKjnUSaxNxdQgY9m0SWOkl5c+sT5UEi1Ue8GS/szE9IL0gszMy/9jk0OdxNpUTC/IWDZt0hipF+ReI9n6qr1gSX9mYnpBekFm5qUXZJNaP+CHdItJqUdsOuGVjFG9RIskVrLGG9b/ALqulR+ih9GsAAAAAElFTkSuQmCC";
var imageData = Convert.FromBase64String(x);
var contentId = Guid.NewGuid().ToString();
var linkedResource = new LinkedResource(new MemoryStream(imageData), "image/jpeg")
{
ContentId = contentId,
TransferEncoding = TransferEncoding.Base64
};
var msg = string.Format("<p><label> Visitor's Name: {0}</lebel></p> " +
"<p><label> Person to Visit: {1} </lebel> </p>" +
"<p><label> Department Name: {2} </lebel> </p>" +
"<p><label> Schedule: {3} </lebel></p>" +
"<div>Present this image to the security guard <br /><img src=\"cid:{4}\" /></div>",
emailDetails.VisitorName, emailDetails.PersonToVisit, emailDetails.DepartmentName,
emailDetails.Schedule, contentId);
string result;
try
{
var htmlView = AlternateView.CreateAlternateViewFromString(msg, null, "text/html");
htmlView.LinkedResources.Add(linkedResource);
var mail = new MailMessage();
var smtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("somename#gmail.com");
mail.To.Add(emailDetails.EmailUsed);
mail.Subject = "Itinerary Gate Pass";
mail.Body = msg;
//mail.IsBodyHtml = true;
smtpServer.Port = 587;
smtpServer.Credentials = new NetworkCredential("somename#sommail.com", "soemthing");
smtpServer.EnableSsl = true;
smtpServer.Send(mail);
result = "Message was sent";
}
catch (Exception )
{
result = "Failed sending Email";
}
return result;
}
If I place a break point in the mail.Body = msg; and copy the value of "msg" in "plnkr", I get the formatted html with the image. Can you show me how to do it please. Thank you.
Email clients will not display base 64 images.
You will either have to display the image by setting the src to an online image accessible over the internet
for example
<img src="http://someurl/someimage.jpg" />
or you would have to attach the image and set the src to
<img src="cid:[The name of the image you attached]" />
So if you say for instance added an attachment named logo.jpg to the email, you will do something like
<img src="cid:logo" />
One important factor you need to consider when following the second approach is that certain email clients will cache images, which might cause problems with incorrect images showing.I would suggest you make use of approach one.
If you do not want to save the file to hard drive, you will need to convert the base 64 string to a byte array which is then used to create an attachment object, for example
var bytes = Convert.FromBase64String(x);
Now you can create the attachment
mail.Attachments.Add(New Attachment(New MemoryStream(bytes),attachmentName))
You have to attach your image in order to reference it with a 'cid':
embedImage = File.ReadAllBytes(imagePath)
mail.Attachments.Add(New Attachment(New MemoryStream(embedImage), imageName))
mail.Attachments(0).ContentId = contentId
Edit: If the only way you can "get" your image is as a Base64 string, try with this... Could work, I guess
embedImage = Convert.FromBase64String(x)
I want to convert my resulting txt file into a UTF8 formatted file so I can load it into my Azure SQL DW via Polybase. It is required the source file be in UTF8.
MSDN has an "IO Streaming example" HERE works perfectly for a single job. I am trying to architect an SSIS solution for around 30 tables though. I believe using this method would cause a race condition where the PS script will be locked by 1 SSIS package when another SSIS package needs it.
I am a sql dev, not a .NET dev so please forgive me. How would one convert the above to an SSIS C# Script task assuming I know how to pass parameters into the Script task?
PowerShell Code from MSDN
#Static variables
$ascii = [System.Text.Encoding]::ASCII
$utf16le = [System.Text.Encoding]::Unicode
$utf8 = [System.Text.Encoding]::UTF8
$ansi = [System.Text.Encoding]::Default
$append = $False
#Set source file path and file name
$src = [System.IO.Path]::Combine("<MySrcFolder>","<MyUtf8stage>.txt")
#Set source file encoding (using list above)
$src_enc = $ascii
#Set target file path and file name
$tgt = [System.IO.Path]::Combine("<MyDestFolder>","<MyFinalstage>.txt")
#Set target file encoding (using list above)
$tgt_enc = $utf8
$read = New-Object System.IO.StreamReader($src,$src_enc)
$write = New-Object System.IO.StreamWriter($tgt,$append,$tgt_enc)
while ($read.Peek() -ne -1)
{
$line = $read.ReadLine();
$write.WriteLine($line);
}
$read.Close()
$read.Dispose()
$write.Close()
$write.Dispose()
Update
I found a similar post which I was able to tweak to my needs, I swear I searched high and low before posting. Anyway here is what IS working for me. If you see anyway to improve it please share:
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;
Your code indicates that your are trying to convert an ASCII file to UTF-8 however that article also states the following:
As UTF-8 uses the same character encoding as ASCII PolyBase will also
support loading data that is ASCII encoded.
So my advice to you is to try the file first with Polybase, check for any conversion issues before you spend any time trying to convert the files.
var mySrcFolder = ""; // something from user variables?
var myUtf8stage = ""; // something from user variables?
var myFinalstage = ""; // something from user variables?
// Static variables
var ascii = System.Text.Encoding.ASCII;
var utf16le = System.Text.Encoding.Unicode;
var utf8 = System.Text.Encoding.UTF8;
var ansi = System.Text.Encoding.Default;
var append = false;
// Set source file path and file name
var src = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myUtf8stage));
// Set source file encoding (using list above)
var src_enc = ascii;
// Set target file path and file name
var tgt = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myFinalstage));
// Set target file encoding (using list above)
var tgt_enc = utf8;
using (var read = new System.IO.StreamReader(src, src_enc))
using (var write = new System.IO.StreamWriter(tgt, append, tgt_enc))
{
while (read.Peek() != -1)
{
var line = read.ReadLine();
write.WriteLine(line);
}
}
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;
I m trying to send email having multiple attachments from my website dashboard. However, my code is only able to attach the last file. I m using **WebClient()** to download files from Cloud system and then adding them as attachments.
This is the code I have written:
foreach (var link in attachments)
{
var uri = new Uri(link);
var s = uri.Segments[1];
var tempDirectory = #"c:\tempFolder\" + #"\"+ s;
WebClient webClient = new WebClient();
webClient.DownloadFile(link, tempDirectory);
Attachment attachment = new Attachment(tempDirectory);
attachment.ContentDisposition.Inline = true;
attachment.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
attachment.ContentId = model.Id.ToString();
attachment.ContentType.Name = s;
email.Attachments.Add(attachment);
}
Any help would be appreciated
EDITED:
I attached two files, so getting these links in each loop:
Loop 1:
abc.com/TestEmail1.txt
Loop 2:
abc.com/TestEmail2.txt
Removing these lines has solved my problem
attachment.ContentDisposition.Inline = true;
attachment.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
attachment.ContentId = model.Id.ToString();
attachment.ContentType.Name = s;
I have the following code:
string imageSrc = "C:\\Documents and Settings\\menonsu\\Desktop\\screenScrapper\\Bitmap1.bmp";
oMsg.HTMLBody = "<HTML><BODY><img src = \" cid:Bitmap1.bmp#embed \"/><br><font size=\"2\" face=\"Courier New\">" + introText + "</font>" + body + "<font size=\"2\" face=\"Courier New\">" + conclText + "</font>" + " </BODY></HTML>";
Microsoft.Office.Interop.Outlook.Attachment attc = oMsg.Attachments.Add(imageSrc, Microsoft.Office.Interop.Outlook.OlAttachmentType.olEmbeddeditem, null, "");
attc.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", "Bitmap1.bmp#EMBED");
//Send the message.
oMsg.Save();
For some reason the email is just showing an x when i try to run this code...anyone know why?
The following is working code with two ways of achieving this:
using System;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Method1();
Method2();
}
public static void Method1()
{
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = "This is the subject";
mailItem.To = "john#example.com";
string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed
var attachments = mailItem.Attachments;
var attachment = attachments.Add(imageSrc);
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/jpeg");
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "myident"); // Image identifier found in the HTML code right after cid. Can be anything.
mailItem.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8514000B", true);
// Set body format to HTML
mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
string msgHTMLBody = "<html><head></head><body>Hello,<br><br>This is a working example of embedding an image unsing C#:<br><br><img align=\"baseline\" border=\"1\" hspace=\"0\" src=\"cid:myident\" width=\"\" 600=\"\" hold=\" /> \"></img><br><br>Regards,<br>Tarik Hoshan</body></html>";
mailItem.HTMLBody = msgHTMLBody;
mailItem.Send();
}
public static void Method2()
{
// Create the Outlook application.
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
//Add an attachment.
String attachmentDisplayName = "MyAttachment";
// Attach the file to be embedded
string imageSrc = "D:\\Temp\\test.jpg"; // Change path as needed
Outlook.Attachment oAttach = mailItem.Attachments.Add(imageSrc, Outlook.OlAttachmentType.olByValue, null, attachmentDisplayName);
mailItem.Subject = "Sending an embedded image";
string imageContentid = "someimage.jpg"; // Content ID can be anything. It is referenced in the HTML body
oAttach.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001E", imageContentid);
mailItem.HTMLBody = String.Format(
"<body>Hello,<br><br>This is an example of an embedded image:<br><br><img src=\"cid:{0}\"><br><br>Regards,<br>Tarik</body>",
imageContentid);
// Add recipient
Outlook.Recipient recipient = mailItem.Recipients.Add("john#example.com");
recipient.Resolve();
// Send.
mailItem.Send();
}
}
}
From what I can tell, you are not setting the content id properly. Try to change the code to the following:
attc.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x370E001F", "image/bmp");
attc.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "Bitmap1.bmp#EMBED");
I have done this before a little differently. I embedded images in some emails that I had to send from my web app using an 'alternate view' in the system.net.mail
System.Net.Mail.LinkedResource theContent = new System.Net.Mail.LinkedResource({path to image});
theContent.ContentID = "TheContent";
String altViewString = anEmail.Body.replace("{original imageSource i.e. '../Images/someimage.gif'}","cid:TheContent");
System.Net.Mail.AlternateView altView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(altViewString, Nothing, System.Net.Mime.MediaTypeNames.Text.Html);
altView.LinkedResources.add(theContent);
anEmail.Message.AlternateViews.Add(altView);
Here's a simple solution:
private static void insertPictureAsLink(Outlook.MailItem mail, String imagePath, String URI)
{
mail.BodyFormat = OlBodyFormat.olFormatHTML;
mail.HTMLBody += String.Format("<body></body>", imagePath, URI);
mail.Display(false);
}
i'm uploading a document to sharepoint.. however i would like to provide a custom name rather than it inherit the name of the file which im uploading.
my code was based on this solution: http://www.codeproject.com/Articles/103503/How-to-upload-download-a-document-in-SharePoint-20.aspx
however this doesnt work.
Additionally, i would also like to provide a title of the file:
so i wanted to update the title:
uploadFile.ListItemAllFields.FieldValues["Title"] = "my custom title";
However, once the file has completed its upload..i login to sharepoint and notice the title hasnt been applied.
how can i intergrate uploading the file and applying a new name?
many thanks,
EDIT:
using (var clientContext = GetNewContext())
{
var uploadLocation = string.Format("{0}{1}/{2}", SiteUrl, Helpers.ListNames.RequestedDocuments, Path.GetFileName(document));
//Get Document List
var documentslist = clientContext.Web.Lists.GetByTitle(Helpers.ListNames.RequestedDocuments);
var fileCreationInformation = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(document), //Assign to content byte[] i.e. documentStream
Overwrite = true, //Allow owerwrite of document
Url = uploadLocation //Upload URL,
};
var uploadFile = documentslist.RootFolder.Files.Add(fileCreationInformation);
uploadFile.ListItemAllFields.FieldValues["Title"] = title;
uploadFile.ListItemAllFields.Update();
clientContext.ExecuteQuery();
}
site.SubmitChanges(ConflictMode.FailOnFirstConflict, true);
You are missing a call to clientContext.Load after you add the file to the Files collection. See these blog posts for more information:
https://www.c-sharpcorner.com/code/965/programmatically-upload-document-using-client-object-model-in-sharepoint.aspx
https://zimmergren.net/sp-2010-uploading-files-using-the-client-om-in-sharepoint-2010/
This code sample is from the first blog post linked above:
public Boolean UploadDocument(String fileName, String filePath, List metaDataList)
{
SP.ClientContext ctx = new SP.ClientContext("http: //yoursharepointURL");
Web web = ctx.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(#"C: \TestFile.doc");
newFile.Url = " / " + fileName;
List docs = web.Lists.GetByTitle("Shared Documents");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();
SPClient.ListItem item = uploadFile.ListItemAllFields;
//Set the metadata
string docTitle = string.Empty;
item["Title"] = docTitle;
item.Update();
context.ExecuteQuery();
}
Are you calling Update after setting the field values?
uploadFile.ListItemAllFields.Update();
instead of setting:
uploadFile.ListItemAllFields.FieldValues["Title"] = title;
uploadFile.ListItemAllFields.Update();
set it as follows:
uploadFile.ListItemAllFields["Title"] = title;
uploadFile.ListItemAllFields.Update();