How to Send automatic emails like newsletter - c#-3.0

I see some question closed by administrator with similar question.
I will try to explain in detail the solution I'm looking for:
First I'm trying to develop a windows console application.
Sending frequency: monday to friday
How many users: from 5 to 20
Format of data:
A table where rows are countries and columns different types of products and the cells represent the sale of that country-product
Limitation:
Service users prefer not to use a pdf or excel or attachment of any type should be a html format possible to show in the body of mail
Currently I am creating the report almost artisan with something like:
.....
var myStringBuilder = new StringBuilder("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
myStringBuilder.Append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">");
myStringBuilder.Append("</head><body>");
myStringBuilder.AppendLine();
myStringBuilder.Append("<table style=\"font-family: Calibri; text-align: right; font-size: x-small;\">");
myStringBuilder.AppendLine();
var header = new StringBuilder("<tr><th>a</th><th>CATEG1</th><th>CATEG2</th><th>CATEG3</th><th>CATEG4</th><th>TOTAL</th></tr>");
var line = new StringBuilder("<tr><td>a</td><td>b</td><td>c</td><td>z</td><td>e</td><td>f</td></tr>");
foreach (var a in _actuals)
{
line.Replace("a", a.CountryName);
if(a.Segment.ToLowerInvariant().Equals("categ1")) {
line.Replace("b", "[" + string.Format("{0:0,#}", a.LsvLcFact / 1000) + "]"); }
else if (a.Segment.ToLowerInvariant().Equals("categ2")) {
line.Replace("c", "[" + string.Format("{0:0,#}", a.LsvLcFact / 1000) + "]"); }
else if (a.Segment.ToLowerInvariant().Equals("categ3")) {
line.Replace("z", "[" + string.Format("{0:0,#}", a.LsvLcFact / 1000) + "]"); }
else {
line.Replace("e", "[" + string.Format("{0:0,#}", a.LsvLcFact / 1000) + "]"); }
}
.....
And in the class to send mail something like:
public void SendResumen(string subject ,StringBuilder content)
{
var oMsg = new MailMessage...;
... add users
oMsg.Subject = subject;
var mimeType = new ContentType("text/html");
var alternate = AlternateView.CreateAlternateViewFromString(content.ToString(), mimeType);
oMsg.AlternateViews.Add(alternate);
oMsg.IsBodyHtml = true;
var cli = Client();
cli.Send(oMsg);
}
Finally, I hope you understand what I'm doing and the question is:
Is there a tool I can use to not generate as crafted the message body?

I have a VB application that can send out messages that have an HTML payload, and it doesn't use the AlternateView functionality.
Dim mail As New MailMessage(fromUser.Email, toUser.Email)
mail.Subject = subject
mail.IsBodyHtml = True
mail.Body = message
While it would be nice to use the AlternateView functionality for those email clients that can't read the HTML payload, your code can't really use it because you're only supplying an HTML message. If you did manage to get the AlternateView functionality to work here, any client that couldn't read HTML would see the HTML markup instead of just simple message text. For this to truly work, I think you would need to provide both a text and HTML email message body.

I Accept the suggest from #Jim-Mischel

Related

Trying to send email automatically of a Google Docs created through apps script

Using script I replaced body txt in a copied doc. I want to get that doc id and send that via email automatically after doc was created. Not sure if its possible but my current code is below. Please help.
var templateFile = DriveApp.getFileById("1baIoahNT9YJ84mnUcp1pyWR0U5v235z29vPCkiv4rIc");
var templateResponseFolder = DriveApp.getFolderById("1mmFKjNnbTy2k8ZWobtcvdtIcwyse3NVd");
var copy = templateFile.makeCopy(deptName + " " + "Cost Recovery Agreement", templateResponseFolder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText("{{DeptName}}", deptName);
body.replaceText("{{DeptCo}}", deptCo);
body.replaceText("{{FirstName}}", firstName);
body.replaceText("{{LastName}}", lastName);
doc.saveAndClose();
var id = doc.getId();
var subject = "Welcome to ResponseMaster!";
var message = title + " " + lastName + "," + "\n\n" + "Thank you for choosing ResponseMaster as your dedicated software for your fire department.";
var costRecoveryForm = DriveApp.getFileById();
MailApp.sendEmail(userEmail, subject, message, { attachments: [costRecoveryForm] });
I am already have the e.values set up properly further above the script but this is all the script that deals with the issue.
By putting the Google Doc URL in the email body, Gmail will show it as an attachment (if the recipient has access to the file).
Like in the following image.
So here is my approach:
let templateFile = DriveApp.getFileById("1hNJ8SUybJn8nnJg87Pm22dzI0_3L0N17ZbYhV1HeUrM");
let templateResponseFolder = DriveApp.getFolderById("1Xzs1k-e8q2NYCTHg-4yit7zFWTF7L33h");
let copy = templateFile.makeCopy(`${deptName} Cost Recovery Agreement`, templateResponseFolder);
let copyId = copy.getId();
// Here I give the user permission to view the file I'm sending him
DriveApp.getFileById(copyId).addViewer(userEmail);
let doc = DocumentApp.openById(copyId);
let copyUrl = doc.getUrl();
let body = doc.getBody();
body.replaceText("{{DeptName}}", deptName);
body.replaceText("{{DeptCo}}", deptCo);
body.replaceText("{{FirstName}}", firstName);
body.replaceText("{{LastName}}", lastName);
doc.saveAndClose();
let subject = "Welcome to ResponseMaster!";
let message = `${title} ${lastName},\n\nThank you for choosing ResponseMaster as your dedicated software for your fire department.\n\n${copyUrl}`;
MailApp.sendEmail(userEmail, subject, message);

Is it possible to send page content via email using UI5?

My application is designed to create a table which is later edited by the user. After this I need my application to send the page content via email.
I used URLHelper's trigger email() but through this I am able to trigger the email with to, cc, subject, text body but my ui5 application is not able to insert the table into the email.
Can someone please suggest something? or is it even possible?
I won't mind using plain javascript either, Point is I need to do this without using the backend.
We do something similar on one of our apps. I added a button to the screen which when clicked invokes a 'mailto', and populates the email client with the to, subject and body. The body is created as part of the script. We basically read the table contents into an array, then loop through the entries using a forEach. Keep in mind using mailto or even the URLHelper does not allow you to use HTML formatted text in the 'body' of the email. So, if you're looking for something pretty, you may be out of luck.
onNotifyUserPress: function(oEvent) {
var oItem = oEvent.getSource();
var oBinding = oItem.getBindingContext();
// Set some vars for the email package
var sEmpEmail = oBinding.getProperty("Smtp");
var sEmpName = oBinding.getProperty("STEXT_2");
var sEmailSubject = "Your Subject " + sEmpName;
// Create DateFormat Object
var oDateFormat = DateFormat.getDateTimeInstance({pattern: "dd/MM/yyyy"});
// Retrieve Table Data
var oTable = this.getView().byId("yourTable");
var aTableData = oTable.getBinding("items").getContexts();
// Build the email body
var sBody = sEmpName + " - Some Body Text\n\n";
sBody += "Field 1 | " + "Field 2 | " + "Field 3 | " + "Field 4" + "\n";
// Loop through table data and build the output for the rest of the email body
aTableData.forEach(function(oModel) {
var oModelData = oModel.getObject();
var sEndDate = oDateFormat.format(oModelData.Vendd);
var sStatus = this._formatStatus(oModelData.ZQ_STAT);
sBody += (oModelData.Essential === "X" ? "Yes" : "No") + " | " + oModelData.Ttext + " | " + sEndDate + " | " + sStatus + "\n";
}.bind(this));
// Open email client window and prepopulate with info
window.open("mailto:" + sEmpEmail + "&subject=" + sEmailSubject + "&body=" + encodeURIComponent(sBody), "_self");
},
You'll obviously need to update the code to point to your table data. In this particular instance, we have an object page with a couple of sections. Each section contains a table which loads a list of entities that are associated with the user. As the data is already loaded and exists in the model, this may not work in the same fashion as what you're trying to do (if I understand correctly), as you need to send an email after the data is entered/modified?
Hopefully this can at least get you started!
Cheers!

Generate and download file from Word dialog

Is there a way to generate a file with some JSON content and prompt the user with a saveAs dialog.
This is from an open dialog in word.
The object could be like (will be quite a lot bigger in practice)
var obj = {a: 1, b: 2, c: 'qwerty'}
I tried to uri encode and using window.open without any luck.
content = JSON.stringify(obj);
uriContent = "data:application/octet-stream," + encodeURIComponent(content);
newWindow = window.open(uriContent, 'filename');
I did this for XML, but it requires some back-end and front-end work. On the backend, you need some ASPX like this:
string filename = "export.xml";
byte[] data = Convert.FromBase64String(Request.QueryString[0].Replace("\"", ""));
string decodedString = System.Text.Encoding.UTF8.GetString(data);
// set the http content type to "APPLICATION/OCTET-STREAM
Response.ContentType = "APPLICATION/OCTET-STREAM";
System.String disHeader = "Attachment; Filename=\"" + filename + "\"";
Response.AppendHeader("Content-Disposition", disHeader);
Response.Flush();
Response.Write(decodedString);
I called mine "download.aspx." Then on the front-end, you have to use AJAX. This created a form region on the page and the forces a submit of the form to start the download:
// Helper function to load a form and then send the post results to a
// new window so that we can get the download button
function ajax_download(url, data, input_name) {
try {
$('#form-div').append("<form method='GET' action='" +
url + "' target='_blank'>" +
"<input type=hidden name='" + input_name + "' value='" +
JSON.stringify(data) + "'/></form>");
$('#form-div').find('form').submit();
} catch (err) {
showNotification("error", err.description);
}
}
To call it, you simply make this this call from your JavaScript code where you want it:
xml = "<xml><data>12345</data></xml>";
ajax_download('./Download.aspx', btoa(xml), 'xml');
In this case, mine is targeting XML and always creates a file called "export.xml", but you can adjust it as needed.

Send Email fields not rendering in Sitecore Web Forms For Marketers

I have an issue with the WFFM Send Email Message save action (Sitecore 6.5.0). I'm trying to send an email that includes the form placeholders from the "Insert Field" dropdown in the Send Email editor. Sometimes the fields will render correctly, but most times the email will include the placeholder text instead of the field's actual value.
For example, this is the email that is coming through:
First Name: [First Name]
Last Name: [Last Name]
Email: [Email Address]
Company Name: [Company Name]
Phone Number: [Phone Number]
I think it has to do with the Send Email editor using a rich text editor for the email template, but I've tried adjusting the message's HTML to no avail. This is what the markup looks like: (the <p> tags and labels used to be inline, but that didn't work either)
<p>First Name:
[<label id="{F49F9E49-626F-44DC-8921-023EE6D7948E}">First Name</label>]
</p>
<p>Last Name:
[<label id="{9CE3D48C-59A0-432F-B6F1-3AFD03687C94}">Last Name</label>]
</p>
<p>Email:
[<label id="{E382A37E-9DF5-4AFE-8780-17169E687805}">Email Address</label>]
</p>
<p>Company Name:
[<label id="{9C08AC2A-4128-47F8-A998-12309B381CCD}">Company Name</label>]
</p>
<p>Phone Number:
[<label id="{4B0C5FAC-A08A-4EF2-AD3E-2B7FDF25AFA7}">Phone Number</label>]
</p>
Does anyone know what could be going wrong?
I have encountered this issue before, but was using a custom email action. I managed to fix it by not using the deprecated methods in the SendMail class and instead using the
Sitecore.Form.Core.Pipelines.ProcessMessage namespace's ProcessMessage and ProcessMessageArgs classes.
My use case was a little more complicated than yours, as we were also attaching a PDF brochure to our message (which is why we were using the custom email action in the first place), but here is the code:
public class SendBrochureEmail : SendMail, ISaveAction, ISubmit
{
public new void Execute(ID formId, AdaptedResultList fields, params object[] data)
{
try
{
var formData = new NameValueCollection();
foreach (AdaptedControlResult acr in fields)
{
formData[acr.FieldName] = acr.Value;
}
var senderName = formData["Your Name"];
var emailTo = formData["Recipient Email"];
var recipientName = formData["Recipient Name"];
var documentTitle = formData["Document Title"];
if (documentTitle.IsNullOrEmpty())
{
documentTitle = String.Format("Documents_{0}", DateTime.Now.ToString("MMddyyyy"));
}
Subject = documentTitle;
if (!String.IsNullOrEmpty(emailTo))
{
BaseSession.FromName = senderName;
BaseSession.CatalogTitle = documentTitle;
BaseSession.ToName = recipientName;
var tempUploadPath = Sitecore.Configuration.Settings.GetSetting("TempPdfUploadPath");
var strPdfFilePath =
HttpContext.Current.Server.MapPath(tempUploadPath + Guid.NewGuid().ToString() + ".pdf");
//initialize object to hold WFFM mail/message arguments
var msgArgs = new ProcessMessageArgs(formId, fields, MessageType.Email);
var theDoc = PdfDocumentGenerator.BuildPdfDoc();
theDoc.Save(strPdfFilePath);
theDoc.Clear();
FileInfo fi = null;
FileStream stream = null;
if (File.Exists(strPdfFilePath))
{
fi = new FileInfo(strPdfFilePath);
stream = fi.OpenRead();
//attach the file with the name specified by the user
msgArgs.Attachments.Add(new Attachment(stream, documentTitle + ".pdf", "application/pdf"));
}
//get the email's "from" address setting
var fromEmail = String.Empty;
var fromEmailNode = Sitecore.Configuration.Factory.GetConfigNode(".//sc.variable[#name='fromEmail']");
if (fromEmailNode != null && fromEmailNode.Attributes != null)
{
fromEmail = fromEmailNode.Attributes["value"].Value;
}
//the body of the email, as configured in the "Edit" pane for the Save Action, in Sitecore
msgArgs.Mail.Append(base.Mail);
//The from address, with the sender's name (specified by the user) in the meta
msgArgs.From = senderName + "<" + fromEmail + ">";
msgArgs.Recipient = recipientName;
msgArgs.To.Append(emailTo);
msgArgs.Subject.Append(Subject);
msgArgs.Host = Sitecore.Configuration.Settings.MailServer;
msgArgs.Port = Sitecore.Configuration.Settings.MailServerPort;
msgArgs.IsBodyHtml = true;
//initialize the message using WFFM's built-in methods
var msg = new ProcessMessage();
msg.AddAttachments(msgArgs);
msg.BuildToFromRecipient(msgArgs);
//change links to be absolute instead of relative
msg.ExpandLinks(msgArgs);
msg.AddHostToItemLink(msgArgs);
msg.AddHostToMediaItem(msgArgs);
//replace the field tokens in the email body with the user-specified values
msg.ExpandTokens(msgArgs);
msg.SendEmail(msgArgs);
//no longer need the file or the stream - safe to close stream and delete delete it
if (fi != null && stream != null)
{
stream.Close();
fi.Delete();
}
}
else
{
Log.Error("Email To is empty", this);
throw new Exception("Email To is empty");
}
}
catch (Exception ex)
{
Log.Error("Test Failed.", ex, (object) ex);
throw;
}
finally
{
BrochureItems.BrochureItemIds = null;
}
}
public void Submit(ID formid, AdaptedResultList fields)
{
Execute(formid, fields);
}
public void OnLoad(bool isPostback, RenderFormArgs args)
{
}
}
It is very possible that the Email Action that WFFM ships with is using the deprecated methods, which could be your problem. I do not have time to look into it, but you can decompile the DLL and look to see what their Email Action is doing. Regardless, the above code should work out of the box, save for updating the fields to those that you are using and removing the code for attaching the PDF, should you choose to not have attachments.
Good luck, and happy coding :)
If you change a field on the form in any way (caption, name, type, etc) the link will change and you need to re-insert the placeholder and move it up to its location in your expected email. This is also true if you duplicate a form. You'll have to reinsert all the fields in the email or you will just get the outcome you show above.
Reinserting upon a change will ensure the value is collected!

Email form responses, but do not include blank responses

So I am using a script i found on line to send an email everytime a Google Form is completed, which includes the data in the form via a Google Sheet.
function sendFormByEmail(e)
{
var email = “email#address.com”;
var s = SpreadsheetApp.getActiveSheet();
var headers = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = "A new travel request has been submitted.";
var subject = "New Travel Justification Request: ";
for(var i in headers)
message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";
subject += e.namedValues[headers[2]].toString() + " - starts " + e.namedValues[headers[15]].toString();
MailApp.sendEmail(email, subject, message);
// Based off of a script originally posted by Amit Agarwal - www.labnol.org
// Credit to Henrique Abreu for fixing the sort order
}
It works well, but I want it to exclude the headers for empty cells, as not all parts of the form require completion.
I know very little, so all help is appreciated.
I have updated the original Google Form script to not include fields that are empty. You can add a simple condition in the for loop:
for(var i in headers) {
if ( e.namedValues[headers[i]].toString() != "") {
message += headers[i] + ': '+ e.namedValues[headers[i]].toString() + "\n\n";
}
}