+ Start a Discussion
Bernd NawrathBernd Nawrath 

Email trigger with visualforce

Good evening dear community, I was programming an email trigger that sends a template attached with a pdf autimatically when a new account is added. I have a main class, a test class, the trigger and an email template to test it so far but when I am running the test class to check if it works I get this exception:

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Account.PersonEmail

What can I do ? If you need more information please let me know because this very important to me. 

This is the code:
(Main class)
public class HelperContactTrigger {
    //static method
    public static List<Account> sendEmail(List<Account> accounts) {

        //query on template object
        EmailTemplate et=[Select id from EmailTemplate where name= 'MCM'];

        system.debug(et);   //debug to check the template

        //list of emails
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();

        for(Account con : accounts){

            //check for Account
            if(con.PersonEmail == null && con.PersonEmail != null){

                //initiallize messaging method
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();

                //set object Id

                //set template Id

                //flag to false to stop inserting activity history

                //add mail

        //send mail

        return accounts;

(Test class)
private class HelperContactTriggerTestneu {
public static testMethod void myTestMethod() {

        system.debug('### NewAccountTest ###');
        Account acc = new Account(Name = 'Test Test');
        insert acc;

        List<Account> sendMail = [select id from account where (Name='Test Test') and id=:acc.id];
        System.assert(acc !=null);

Thanks in advance ! :)
Best Answer chosen by Bernd Nawrath
Bhanu MaheshBhanu Mahesh
Hi Bernd,

If you are using any field, we have to include that field in SOQL query while retrieving the records.

Try adding "PersonEmail" field in the query 
List<Account> sendMail = [select id,PersonEmail from account where (Name='Test Test') and id=:acc.id];
Make sure that 'PersonEmail' should be populated with some value.

And also in sendEmail method in class, modify this line if(con.PersonEmail == null && con.PersonEmail != null) to
if(con.PersonEmail != '' && con.PersonEmail != null) because it can't be both ==null and  !=null at the same time.

Bhanu Mahesh