VISUALFORCE /APEX : Simple email feedback form - salesforce

I am developing a site in Visualforce and would like to offer user a simple form to send me feedback via email. There would be 3-4 fields like name, user's email, reason and feedback and "send" button. Clicking the send button should automatically send that message to my email address.
I do not want to store the form data in salesforce at least for now...All the stuff I found online about visualforce/apex and email is about saving that data to salesforce too.
Can I just make use of apex's email capabilities and send out email without storing that data anywhere in salesforce?
Thanks,
Calvin

It's not required to insert/update/delete any records in the database when executing an action on a VisualForce page. You can leverage the Outbound Email functionality to send out your notification. For something like this, you will probably want to familiarize yourself with the SingleEmailMessage methods.
A simple example to get you going:
public PageReference actionSend() {
String[] recipients = new String[]{'myemailaddress#somedomain.com'};
Messaging.reserveSingleEmailCapacity(recipients.size());
Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
msg.setToAddresses(recipients);
msg.setSubject('Test Email Subject');
msg.setHtmlBody('Test body including HTML markup');
msg.setPlainTextBody('Test body excluding HTML markup');
msg.setSaveAsActivity(false);
msg.setUseSignature(false);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {msg}, false);
return null;
}
If you are interested in sending these outbound messages from a dedicated email address (something like noreply#somecompany.com), you can set these up through the Setup -> Administration Setup -> Email Administration -> Organization-Wide Addresses menu. Once you have created an org-wide address, grab the Id from the URL and use the setOrgWideEmailAddressId(Id) method on your instance of Messaging.SingleEmailMessage.

Related

Exception in Site.createExternalUser in Apex RESTclass: Site.ExternalUserCreateException: [That operation is only allowed from within an active site.]

I have a Non-Salesforce Auth System which holds usernames and passwords for a few thousand users. I am willing to migrate these users to Salesforce and give access to these users to my Experience Cloud site. I am developing an apex REST Resource which will take username and password as arguments and create a user with that username and password with a community profile. I am planning to call this API from my Non-Salesforce system and migrate all these users. I am using Site.createExternalUser method in this API. I am getting the exception
Site.ExternalUserCreateException: [That operation is only allowed from within an active site.]
The reason I am using Site.createExternalUser is because I don't want to send the welcome email/reset password email to my users since they already have signed up successfully long ago.
I am open to any alternatives for achiving this.
Below is my code:
#RestResource(urlMapping='/createUser/*')
global with sharing class createUserRestResource {
#HttpPost
global static String doPost(){
Contact con=new Contact();
con.Firstname="First";
con.LastName= "Last";
con.Email="first.last#example.com";
con.AccountId='/Add an account Id here./';
insert con;
usr.Username= "usernameFromRequest#example.com";
usr.Alias= "alias123";
usr.Email= "first.last#example.com";
usr.FirstName= "First";
usr.IsActive= true;
usr.LastName= "Last";
usr.ProfileId='/Community User Profile Id/';
usr.EmailEncodingKey= 'ISO-8859-1';
usr.TimeZoneSidKey= 'America/Los_Angeles';
usr.LocaleSidKey= 'en_US';
usr.LanguageLocaleKey= 'en_US';
usr.ContactId = con.Id;
String userId = Site.createExternalUser(usr, con.AccountId, 'Password#1234', false);
return userId;
}
}
You can suppress sending emails out in whole org (Setup -> Deliverability) or in the Community config there will be way to not send welcome emails (your community -> Workspaces -> Administration -> Emails).
Without running on actual Site I don't think you can pull it off in one go. In theory it's simple, insert contact, then insert user. In practice depends which fields you set on the user. If it's Partner community you might be setting UserRoleId too and that's forbidden. See MIXED DML error. In Customer community you might be safe... until you decide to assign them some permission sets too.
You might need 2 separate endpoints, 1 to create contact, 1 to make user out of it. Or save the contact and then offload user creation to #future/Queueable/something else like that.

Sending emails to multiple users using flows(Salesforce)

I need to send an email notification to the record owner and manager once the opportunity is closed-won.
adding only owner email works fine
adding only manager email works fine
But if I add both together with coma, {!$Record.Owner.Email},{!$Record.Engagement_Manager__r.Email} I'm getting error.
what is the correct way to add it?
You can try creating a Formula Resource in your flow like this but, in your case, using $Record.Owner.Email and $Record.Engagement_Manager__r.Email:
Then, you can use this Resource in your Email Action:
Try the below code and let me know if it works.
global class SendPurchaseOrderEmail {
WebService static void sendEmail(String poId) {
List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
String theTemplate = [SELECT Id FROM EmailTemplate WHERE DeveloperName = 'Purchase_Order_With_Items'].Id;
User theUser = [SELECT Id FROM User WHERE Name = 'user name goes here'];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSaveAsActivity(false);
mail.setTemplateId(theTemplate);
mail.setWhatId(poId);
mail.setTargetObjectId(theUser.Id);
mail.setToAddresses(new String[] { 'TestUser#salesforce.com' ,'abc#test.com'}); //add other emails here.
emails.add(mail);
Messaging.sendEmail(emails);
}
}
Please refer below link for more details.
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_sendemail.htm
This is because you have to pass a direct email address there.
Instead of that, you can create a collection variable, store the emails into it, then pass that variable to email addresses (collection) field.
Note: you can only store upto 5 emails into that colllection variable at a time.
Hi For that you can simply add collection Variable.
For that variable assign multiple values to it. So that you can send email to both record owner as well as manager.
From New Resource Select the Variable and click Allow Multiple Values and Data-type as text.
Then by using Assignment. Add the following email Address to it Please refer the below image.
I hope you have got the solution
Thanks

Meteor sendVerificationEmail

I'm currently working on revising the registration procedure of our recruitment ATS, made with AngularJS and Meteor, and I need to verify the new user's email during the registration procedure.
The logic would go as followed:
1- User fills in a form on the 'get-started' page and when clicking on 'sumbit', the ATS sends a verification email(I'll be using 'sendVerificationEmail' from Meteor)
2- After the user clicks on the link from the email, they'll get redirected to the 'register' page where additional information is required and the registration procedure is concluded.
As mentioned above, I'm planning to use 'sendVerificationEmail' to verify the user but I also want to use it to send back the userID.
From what I read on the Meteor API, I can pass extra data to the token with 'extraTokenData'
Accounts.sendVerificationEmail(userId, [email], [extraTokenData])
Now how do I declare the 'extraTokenData' object?
Could I do it like this: Accounts.sendVerificationEmail(userId, "", { _id: userId })
And how do I retrieve the 'userId' with 'Accounts.onEmailVerificationLink'?
your help will be greatly appreciated.
The email and the extra tokens are optionals, but if you want to send them send it as a string.
If you want to send the extra token but no emails you can try using Accounts.sendVerificationEmail(userId, undefined, "extra token") or if it doesn't work you can request the user's deatil user Meteor.user(). then call user.emails[0].address.
To retrieve information you have to get user by token and all data are there on user document under services.password.reset field. Look here how Accounts.generateResetToken is implemented https://github.com/meteor/meteor/blob/1e7e56eec8414093cd0c1c70750b894069fc972a/packages/accounts-password/password_server.js#L609.

Salesforce- Creating contact and user by importing CSV file & send notification email to User

I want to create the contact & user related to account by importing csv file.After creating user, generated username & password should be send to the respective user's email address.
I am planning to use Vf page for accepting the csv file & the Contact & User API for adding contacts & Users. But I am not sure regarding the email notification to user through API.
So can anyone please provide me the best solution for this?
You'll need to use Database.insert() flavor instead of straightforward insert users;
Check out the DML options help topic, especially the "emailHeader" property
Something like this should do the trick:
List<User> users = new List<User>(); // fill in with data from your CSV
Database.DMLOptions dlo = new Database.DMLOptions();
dlo.EmailHeader.triggerUserEmail = true;
database.insert(users, dlo);
Be aware though that you can't insert an inactive user. You can deactivate them straight after the insert but then they can't login so you'll probably want to suppress the sending of email, not enforce it. Make sure you have sufficient amount of licenses before you start!
Last but not least - you can cheat by setting the same password for them with System.setPassword('user id', 'new password') :) It's not recommended to expose this functionality to your end users though, can process only 1 user at a time and wastes 1 DML statement...

Email verification through silverlight

I've built a Silverlight website where users can create an account and login. Right now, users just create an account through a form and can directly login. I want to incorporate a email verification feature, where the user will receive an email with a verification URL and only then can he login. I also wish to incorporate a forgot password feature that sends an email to the users registered email address to recover password.
How can I do this in silverlight. I'm using Windows SQL Azure as the back-end database. Will I have to create a separate Application for creating user accounts and recovering passwords?
Hope this helps you out on part A of your problem.
I noticed the post might throw you off a bit, so I decided to write a method that will do this for you in the quickest amount of time.
public bool Send(string fromEmail, string toEmail, string subject, string body)
{
try
{
MailMessage message = new MailMessage();
message.From = new MailAddress(fromEmail);
message.To.Add(new MailAddress(toEmail));
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Send(message);
return true;
}
catch (Exception ex)
{
return false;
}
}
Essentially, once they create their account you would want to call this filling out all variables. Make sure in your body of text you have a link that sends them to a page where they can submit "activate" their account.
This will essentially be a bit value in the database that is set to false by default and won't be set to true until they click on the "submit" or "activate" button from the link that would be in the body of text.
For password recovery you would do the same. Except instead of sending them to a page to activate their account you'd send them to a page where they could just re-create their password. Since the database doesn't care if the password is old or new you could just send them to a page where they create a new password. You wouldn't even need to create a temp password for them (Unless you wanted to for experience and for a extra caution).
Happy Coding! ;)

Resources