If/Else Loop and Auto Email - email

New to coding and trying to jump right in!
I have a new list of customers I'm responsible for in a spreadsheet, and I receive an email from someone I don't immediately recognize.
I need to set up a script to:
1. determine if they are in my book of business
2. if they are in my book of business, send a template email regarding next steps (email A)
3. if they are not in my book of business, send a template email that i'm not their POC and redirecting them to relevant resources (email B)
I believe I need to set up a loop (if/else?) to see if the email I received is from a sender on the list, if it is, send email a, if it isn't send email b.
Does anyone have feedback on my stab below? I've set up a dumbie example I will constantly be working on and updating. https://docs.google.com/spreadsheets/d/1HcLluPhRgl0ihQT0GA-ZFj1KsOPHxl0dU08EFlh2Gss/edit#gid=0
For the if/else I believe I would start with
if (CustomerName) {exists Send email A
} else {Send Email B
}
// The code below will send an email with the current date and time.
var now = new Date();
GmailApp.sendEmail("jlennon#gmail.com", "current time", "The time is: " + now.toString());

Related

Emails generated by Googleappscript are skipping my inbox

I have a shared google sheet that when someone enters their info it prompts the next individual with an email that's automatically generated by the script. These emails prompt a dozen individuals and show up as coming from my email. This has functioned perfectly for months.
In the past week or so I've stopped emails have stopped coming to my inbox. The still shows up in "Sent" and also under "All Mail" but I'm not sure if that's just the "sent" message". All other users receive emails normally. Also, if I change my target address to a different email it works fine. Basically, it appears i can't send myself an email.
I have recently started using email filters which I know is the most likely culprit in these situations. None of them currently use the "Skip Inbox" function.
I have no idea why these emails don't show up for me despite working for everyone else as well as if I enter an alternate email address.
Edit #1:
Below is the section of code that emails the next person. As stated it appears to be working perfectly because everyone else except myself gets an email. Also if I change my email to an alternate email that works as well. It appears the issue is solely when the script emails myself from the same email address.
Also, I noted that I was previously receiving emails. This may have been untrue. As a testing measure I previously "CC'd" myself with every email that went out so that I could track that the system was working well. You'll note in the code that my email address is stored in the variable "emailAddress2" and that the CC line has now been commented out. I may not have been receiving the actual email sent to myself before but actually only receiving the CC'd version.
Here's the code:
function emailNext (JustPickedName, NextToPickName, SelectedDate) {
// Function Sends emails to the next Person in the list
Logger.log("Into Email Next");
//Set all the Email characteristics
SelectedDate = Utilities.formatDate(new Date(SelectedDate), "GMT", "EEE, MMM d, yyyy"); //Format the Date for inclusion in the email
var StaffMember = StaffList.find(StaffList => StaffList.Name === NextToPickName);//Find Emails address by finding name in Emails Object
var subject = ' You have a pick pending in the ' + ActiveWeekSheetName + ' sheet';
var message =
'<p>Dear Dr. ' + NextToPickName + '</p>' +
'<p>You have a pick pending on ' + SelectedDate + '. Please look at the ' + ActiveWeekSheetName + ' sheet.</p> <p> Dr. ' + JustPickedName + ' has just made a pick and you are up.</p>' +
'<p>You can make your selection here: GGH Room Selection</p>';
MailApp.sendEmail({
to: StaffMember.Email,
//bcc: emailAddress2,
name: 'PickListBot',
subject: subject,
htmlBody: message})
Logger.log("StaffMember.Email: " + StaffMember.Email);
}
What you are describing might in fact be a bug.
Since this is the case, I suggest you check this issue here on Google's Issue Tracker and star it in order to get any updates with regards to it.

how can I force Google App Script MailApp.sendEmail to use a new thread for each email in a loop?

I am doing a simple app, I have an spread sheet with a few columns, one is an email addres and the others are filled with the information I want to send in an email to that addres. The code is really simple, it is just a while loop with the execution of MailApp.sendEmail with the data in each row.
The issue that I am having is that when I execute the app all the emails end up in the same email threard. And this makes really difficult to follow the responses beacause each email is independet. I've been looking for a while on how to force MailApp.sendEmail to start a new thread, but I can't find how to do it in the documentation or in the web.
The issue is that you are using the exact same subject for these emails and therefore they end up in the same email thread.
For example:
This will put all the emails in the same thread:
function myFunction() {
for (let i=0; i<2; i++){
MailApp.sendEmail("example#gmail.com",
"Test", // subject is the same for every email
"This is an test email");
}
}
This will put the emails in different threads:
function myFunction() {
for (let i=0; i<2; i++){
MailApp.sendEmail("example#gmail.com",
"Test"+i, // subject is different for every email
"This is an test email");
}
}
Instead of using i which is not very well descriptive as a subject, you could send the datetime:
"Test"+new Date()
although this might not work if the emails are sent instantly and therefore the subject will be the same again, but it might work in your case.
Ideally, you would want something that is relevant to the email, for example relevant to the body of your email.

Modifying email templates for Navision 5.0

I've been asked to help do some much needed updates to Microsoft Dynamics NAV 5.0 (yes its old) and they want me to update some of their email templates for sales orders, etc. One of the things they want me to do is update the 'From' field to be a group email box instead of the current user, which I didn't think about be too difficult, but figuring out how NAV creates emails has been less than simple.
This article had some information, but didn't get me all the way there:
http://www.dynamics101.com/2014/02/sending-customized-emails-dynamics-nav/
I've found the Sales Header table which has lots of fields...none of which include "From". I found one field called "Assigned User" which points to the User Setup.
Do you mean the mails that are sent on the event of sales order approval / rejection or that small 'New Mail Message' button in the Customer card? Libraries that are used in these cases are different, and they rely on different automation objects to create e-mail messages.
Anyway, in both cases there is no setup to change the 'From' field - you'll have to customize it a bit.
First of all, you'll need a new field in a setup table to store the e-mail address. Table 'User Setup' is probably the best place, but it depends on the task, of course. Suppose, it is Uset Setup, and you call the new field 'FromAddress'
When you click on the e-mail button in the Customer card, 'Create Mail' wizard is run (Form 5148 'Create Mail'). It calls the function 'NewMessage' in codeunit 397. So, codeunit 397 'Mail', is what you are looking for. To change the 'From' address you need to set the property 'SentOnBehalfOfName' in the OSendMail object.
UserSetup.GET(USERID);
OSendMail.SentOnBehalfOfName(UserSetup.FromAddress);
If the message you want to change is the document approval notification, e-mail message is created in the codeunit 400 'SMTP Mail', but all fields are set up in the codeunit 440 'Approvals Mgt Notification', functions SetTemplate and GetEmailAddress. It is GetEmailAddress that sets the sender address. You need to replace this line of code:
SenderAddress := UserSetup."E-Mail";
with the new one
SenderAddress := UserSetup.FromAddress;
But be careful - this change will affect all templates and all users. If you need to change some templates while leaving other untouched, it is safer to redefine the value of this variable in a function responsible for the particular template. But again, it's all in codeunit 440.

Get sender email address in Infopath

I have a form sent by email that travels through different persons like this.
Person A --> Person B --> Person C
I want the person A to be informed when the form is treated by person C. So Person A needs to be in copy of the email sent by person B.
Because person A isn't always the same one, I think the best way to put him/her in copy is to use the "from" field of the email received by person B and to put it in copy.
But how can I find this address with infopath and how can I place it into my email data connection ?
I had this same question today myself and could not find much in the way of answers.
So... I did some work myself and came up with a few solutions.
First I don't believe there is any way to get/set the "From" address using the InfoPath OM. This means you will have to use one of the following options:
No Code:
You will be limited to providing a field on the form where "Person A" can put their email address and use this in the CC. for subsequent stages. That's kind of the only way and while it an extra burden to the user it does have the benefit of providing flexibility.
Code:
Write your own code to send the mail using Outlook Interop or System.Net.Mail and then you will be setting all of the addresses manually anyway.
If you are using AD or something else then you could always get the email address of the current use using System.DirectoryServices.AccountManagement.
Based on an assumption which I cannot find any documentation to back up. That InfoPath uses the account associated with the default store to send email using EmailSubmitConnection. You should be able to use Outlook Interop to find the address that InfoPath will use.
Here is a code sample:
using Outlook = Microsoft.Office.Interop.Outlook;
public string GetDefaultSenderAddress()
{
// This actually opens outlook in the same way as InfoPath does to send the message.
// which can be slow.
string DefaultAddress = string.Empty;
Outlook.Application OutlookApplication = new Outlook.Application();
string DefaultStoreId = OutlookApplication.Session.DefaultStore.StoreID;
foreach (Outlook.Account Account in OutlookApplication.Session.Accounts)
{
if (Account.DeliveryStore.StoreID == DefaultStoreId)
{
DefaultAddress = Account.SmtpAddress;
}
}
// Note you probably won't want to quit if you are about to send the email.
// However I have noticed that this doesn't seem to close Outlook anyway.
OutlookApplication.Quit();
return DefaultAddress;
}
You may have to provide a few more checks in case of different account types etc. But I believe it will work. (I tested it for my scenario and it does).
Note: Of course this opens an outlook instance which you will have to close as well. And it can be slow. Unless outlook is already open in which case it will be very quick. Anyhow when sending from InfoPath Outlook will have to be opened so if you do this just before sending then there should be no noticeable difference.
I would advise using a combination of the no code/with code options so provide a return address which is automatically complete to save the user time. But can be corrected if the user wishes to have the email returned to a different address of if there is a mistake.
Hope that you find that useful.

Changing the From field for an email activity in a plug-in

When an email is sent to a queue and there is a contact associated with the "From" email in CRM, upon promoting an email to an email activity the system automatically fills in the "From" field with the contact information. However, if a user with the same email exists in CRM, too, then the system always picks up the system user instead of the contact. I need to override this behaviour to ALWAYS pick up the contact if one with the email exists.
I created a post-operation plug-in (tried a pre-operation plug-in, too) for the event Create for email, trying to override the From field. The problem is, it does not work. When I debug the plug-in, it goes quietly past the assignment without any errors and then the same plug-in fires for the same email again. And again. And again.
When I try instead to create a new email and use the same ActivityList[] I was trying to use for the entity that triggered the event, it works. It seems that the problem is that CRM does not allow changing the From field from a plug-in, or am I doing something wrong? If it's a limitation enforced by CRM, is there a way around it?
My code is below:
var email = ((Entity)context.InputParameters["Target"]).ToEntity<Email>();
...
var oldFrom = ((EntityCollection)email.Attributes["from"]).Entities;
List<ActivityParty> newFrom = new List<ActivityParty>();
foreach (Entity party in oldFrom)
{
EntityReference entRef = (EntityReference)party.Attributes["partyid"];
if (entRef.LogicalName == SystemUser.EntityLogicalName)
user = userLogic.Get(new Guid(entRef.Id.ToString()));
if (user == null) return;
string emailAddress = user.InternalEMailAddress;
Contact contact = contactLogic.LookupPASIndividual("", emailAddress);
if (contact != null)
{ newFrom.Add(new ActivityParty() {PartyId = new EntityReference(Contact.EntityLogicalName, contact.ContactId.Value) });
}
else
return;
}
email.From = newFrom;
Update: So I registered the plug-in on Pre-validation now and it's not triggered when an email activity is created by a router, it IS triggered when a user creates an email in CRM though...
The problem is that you aren't changing the email which is processed at all.
var email = ((Entity)context.InputParameters["Target"]).ToEntity<Email>();
This line converts the record which is currently processed to an object of type email. You modify the record which is not in scope of the operation. You have to modify the From of the target (either directly or write it back).
For the processing stages: take a look at the Event Execution Pipeline. Pre-Validation is to early for your task. I'am not quite sure when the address resolution is done, but I would try to do your conversion Pre-Create.
I ended up using a workaround: created an async Post-Event that associates the email activity with the contact if a contact with the same email exists, leaving the user associated with the email in the "From" field.