[SalesForce] how to write a mass email in apex code i have tried if any know what error in this can u solve this

public PageReference send()
    {
        List<Contact> contacts=[Select Id,Email From Contact Where AccountId='001i000000g7erl'];
        List<Id> Conids=new List<string>();
        for(Contact mail: contacts)
        {
            Conids.add(mail.Email);
        }
        //String[] address=new String[]{'Conids'};
        Messaging.MassEmailMessage emails=new Messaging.MassEmailMessage(); 
        emails.setTargetObjectIds(Conids);
        emails.setTemplateId('00Xi0000000J9hx');
        emails.setsubject('note');
        //emails.setplainTextBody('body');
        //emails.setToaddress(address);
        Messaging.SendEmail(New Messaging.MassEmailMessage[] {emails});

return null;
}

this my error::System.StringException: Invalid id: vivek@gmail.com
Error is in expression '{!send}' in component in page brand

Best Answer

Here is something closer to what you would need. There are definately some best practice updates such as bulkifying your process so that you can send a list of accounts to the method, querying for a map so that you can eliminate a loop, and querying for the email template rather than hard coding an id.

    public PageReference send(List<Account> accountIds)
    {
        Map<Id, Contact> contactMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE AccountId IN :accountIds]);

        EmailTemplate template =  [SELECT Id, Name FROM EmailTemplate WHERE DeveloperName = 'My_Unique_API_Name' LIMIT 1];

        Messaging.MassEmailMessage emails=new Messaging.MassEmailMessage(); 
        emails.setTargetObjectIds(contactMap.keySet());
        emails.setTemplateId(template.Id);
        emails.setsubject('note');
        Messaging.SendEmail(New Messaging.MassEmailMessage[]{emails});

        return null;
    }

Remember to select this as an answer if it corrects the issue you are experiencing.

Related Topic