+ Start a Discussion
Zander ZumbrunnenZander Zumbrunnen 

sendEmail() not working more than once

Hello, 

I am trying to send an email at the push of a button using LWC and Apex.
This is my current Apex function that sends the email, this is where I'm guessing the problem is.
@AuraEnabled(cacheable=true)
    public static Boolean sendResources(String email, Id accountId) {
        List<Selected_Resource__c> resources = new List<Selected_Resource__c>([SELECT Name, Name__c, Description__c, Phone__c, Street_Address__c, City__c, State__c, Zip__c 
                                                                               FROM Selected_Resource__c 
                                                                               WHERE Account__c = :accountId AND Active__c = True
                                                                               ORDER BY CreatedDate Desc 
                                                                               LIMIT 10]);
        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setToAddresses(new String[] {email});
        message.setReplyTo('example@example.com');
        message.setSenderDisplayName('Example');
        message.setSubject('Selected Resources');
        String body = '';
        for (Integer i = 0; i < resources.size(); i++) {
            body = body + '<h2>' + resources[i].Name__c + '</h2><p>' + 'Description: ' + resources[i].Description__c + '</p><p>' + 'Phone: ' + resources[i].Phone__c.substring(0, 3) + '-' + resources[i].Phone__c.substring(3, 6) + '-' + resources[i].Phone__c.substring(6, 10) + '</p><p>' + 'Address: ' + resources[i].Street_Address__c + ', ' + resources[i].City__c + ', ' + resources[i].State__c + ' ' + resources[i].Zip__c +'</p>
</br>';
        }
        message.setHtmlBody(body);
        Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
        Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
        if (results[0].isSuccess())
            return true;
        else
            return false;
    }
I am able to get an email the first time I call this but every time after that it will return true but not actually send the email.

Am I missing something here?
 
ShirishaShirisha (Salesforce Developers) 
Hi Zander,

Greetings!

Have you captured the debug logs to see,if there is any issue in the next transaction.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_debugging_debug_log.htm

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
Zander ZumbrunnenZander Zumbrunnen
Hmm, after checking the logs it looks like it isn't being called after the first time clicking the button.

Here is some more information about my project, I have a modal with an email input and a next button. When the button is clicked it creates a certain number of records depending on a list called selected resources. After the last record is created it updates the account with the email and calls that send email function if an email was inputted. I put in some toast messages for lazy debugging, every time I click the button both success toast messages are shown (first one being used to show that the right part of the if statement is being called every time and the second one being used to show that the email should have been sent). Since the second toast message was in the .then of the apex function I assumed it was being called.

Since that button updates the account and sends the email there should be 2 logs every time but after the first press only the update logs show up.

Here is the email input and button in the modal:
<lightning-input type="email" label="" onchange={handleEmailAdd} value={updateInput.fields.Email__c} placeholder="Type Here..."></lightning-input>
<button class="slds-button slds-button_brand" onclick={handleNext} title="Next">Next</button>
Here is the handleNext function:
handleNext() {
		this.isModalOpen = false;
		this.screenLoading = true;
		for (let i = 0; i < this.selectedResources.length; i++) {
			this.recordInput.fields.Name__c = this.selectedResources[i].value.Name;
			this.recordInput.fields.Description__c = this.selectedResources[i].value.Description;
			this.recordInput.fields.Phone__c = this.selectedResources[i].value.Phone;
			this.recordInput.fields.Street_Address__c = this.selectedResources[i].value.BillingStreet;
			this.recordInput.fields.City__c = this.selectedResources[i].value.BillingCity;
			this.recordInput.fields.State__c = this.selectedResources[i].value.BillingState;
			this.recordInput.fields.Zip__c = this.selectedResources[i].value.BillingPostalCode;
			this.recordInput.fields.Food_Bank__c = this.selectedResources[i].value.Food_Bank__c;
			this.recordInput.fields.Financial_Assistance__c = this.selectedResources[i].value.Financial_Assistance__c;
			this.recordInput.fields.Shelter__c = this.selectedResources[i].value.Shelter__c;
			this.recordInput.fields.Case_Management__c = this.selectedResources[i].value.Case_Management__c;
			this.recordInput.fields.Serves_Meals__c = this.selectedResources[i].value.Serves_Meals__c;
			this.recordInput.fields.Senior_Center__c = this.selectedResources[i].value.Senior_Center__c;
			this.recordInput.fields.Housing_Assistance__c = this.selectedResources[i].value.Housing_Assistance__c;
			this.recordInput.fields.Transportation__c = this.selectedResources[i].value.Transportation__c;
			this.recordInput.fields.Social_Services_Assessment__c = this.recordId;
			this.recordInput.fields.Account__c = this.record[0].Account__r.Id;
			this.recordInput.fields.Resource_Account__c = this.selectedResources[i].value.Id;
			createRecord(this.recordInput)
			.then(() => {
				if (i == this.selectedResources.length - 1) {
					if (this.updateInput.fields.Email__c != '') {
						this.dispatchEvent(
							new ShowToastEvent({
								title: "Email",
								message: this.updateInput.fields.Email__c,
								variant: "success"
							}),
						);
						updateRecord(this.updateInput)
						.catch(error => {
							this.error = error;
							this.dispatchEvent(
								new ShowToastEvent({
									title: "Error",
									message: error.body.message,
									variant: "error"
								}),
							);
						});
						sendResources({email: this.updateInput.fields.Email__c, accountId: this.updateInput.fields.Id})
						.then(result => {
							if (result) {
								this.dispatchEvent(
									new ShowToastEvent({
										title: "Sent",
										message: result,
										variant: "success"
									}),
								);
							}
							else {
								this.dispatchEvent(
									new ShowToastEvent({
										title: "Not Sent",
										variant: "error"
									}),
								);
							}
						})
						.catch(error => {
							this.error = error;
							this.dispatchEvent(
								new ShowToastEvent({
									title: "Error",
									message: error.body.message,
									variant: "error"
								}),
							);
						});
					}
					this.selectedResources = [];
					this.noSelectedResources = true;
					this.screenLoading = false;
					this.vfpage = true;
				}
			})
			.catch(error => {
				this.dispatchEvent(
					new ShowToastEvent({
						title: "Error",
						message: error.body.message,
						variant: "error"
					}),
				);
			});
		}
	}


 
Zander ZumbrunnenZander Zumbrunnen
After some more testing, I think it is a timing issue. 

If I try to send the email right after just sending one it does not work, but if I wait a minute or 2 without refreshing and click it again it does send the email.

Is this a known issue? And is there a workaround? I'd rather not have to wait an unknown amount of time before being able to send another email.