Salesfroce single Email send class - salesforce

I had used this class to send an email. but now its not working. i am new for salesforce.
List<String> Address = new List<String>();
Address.add('Email address is here');
mail object code is as following :
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<Messaging.EmailFileAttachment> allApplicantAttachments = new List<Messaging.EmailFileAttachment>();
Messaging.EmailFileAttachment applicantAttachment = new Messaging.EmailFileAttachment();
PageReference pdf = new pagereference('/apex/gernerateInvoicePdf?Id=a12m00000014ADN');
mail.setToAddresses(Address);
mail.setSubject('test');
mail.sethtmlBody('hello');
Blob b = pdf.getContent();
//mail.setBody(b);
applicantAttachment.setBody(b);
applicantAttachment.setFileName('test.html');
allApplicantAttachments.add(applicantAttachment);
mail.setFileAttachments(allApplicantAttachments);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

The code is proper and it works for me. You might setup an email log as mentioned here to see if the email is not getting delivered?
Sreenish

At the end you are trying to send a to a new list. using:
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
try adding your mails to a list first like this :
List<Messaging.SingleEmailMessage> mailToSend = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
List<String> addresses = new List<String>();
addresses.add(emailAddress);
mail.setToAddresses(addresses);
mail.setPlainTextBody(convertList(contactList));
//Add to list then call send with full list
mailToSend.add(mail);
Messaging.sendEmail(mailToSend);

Related

How to write send email test case and read Excel file test case in Selenium

Here is my my code to write a sample send email test case. When running the code email is not getting triggered. Please find attached data for more details
Login User details
Invalid User Details
Booking Data
Can anyone please help to resolve the issue as I am novice in selenium automation testing. Below is sample code of my Java code for configuration and triggering of email.
How to send out an Email notification in Selenium webdriver using Java, whenever some scenario is failed/passed in between?
public class SendEmail {
public SendEmail() {
}
public void email() {
// Create object of Property file
Properties props = new Properties();
// this will set host of server- you can change based on your
// requirement
props.put("mail.smtp.host", "smtp.gmail.com");
// set the port of socket factory
props.put("mail.smtp.socketFactory.port", "465");
// set socket factory
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// set the authentication to true
props.put("mail.smtp.auth", "true");
// set the port of SMTP server
props.put("mail.smtp.port", "465");
// This will handle the complete authentication
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("seleniumtest201#gmail.com", "Admin12!#");
}
});
try {
// Create object of MimeMessage class
Message message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress("seleniumtest201#gmail.com"));
// Set the recipient address
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("aniketgupta1993#gmail.com"));
// Add the subject link
message.setSubject("Test Case Execution Report");
// Create object to add multi media type content
BodyPart messageBodyPart1 = new MimeBodyPart();
// Set the body of email
messageBodyPart1.setText("This is auto-generated test case execution report");
// Create another object to add another content
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
// Mention the file which you want to send
String filename = "C://Users//aniket//sampleseleniumproject//test-output//emailable-report.html";
// Create data source and pass the filename
DataSource source = new FileDataSource(filename);
// set the handler
messageBodyPart2.setDataHandler(new DataHandler(source));
// set the file
messageBodyPart2.setFileName(filename);
// Create object of MimeMultipart class
Multipart multipart = new MimeMultipart();
// add body part 1
multipart.addBodyPart(messageBodyPart2);
// add body part 2
multipart.addBodyPart(messageBodyPart1);
// set the content
message.setContent(multipart);
// finally send the email
Transport.send(message);
System.out.println("=====Email Sent=====");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
You can use following code for the getting email when execution is completed and this put in teardown so you can get an Email notification in selenium webdriver, whenever scenario is failed/passed in between
public void tearDown()
{
private static void sendPDFReportByGMail(String from, String pass, String to, String subject, String body)
{
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
//Set from address
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//Set subject
message.setSubject(subject);
message.setText(body);
BodyPart objMessageBodyPart = new MimeBodyPart();
objMessageBodyPart.setText("Please Find The Attached Report File!");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(objMessageBodyPart);
objMessageBodyPart = new MimeBodyPart();
//Set path to the pdf report file
String filename = System.getProperty("user.dir")+"\\Default test.pdf";
//Create data source to attach the file in mail
DataSource source = new FileDataSource(filename);
objMessageBodyPart.setDataHandler(new DataHandler(source));
objMessageBodyPart.setFileName(filename);
multipart.addBodyPart(objMessageBodyPart);
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

Adding new record to DB through REST API using Angularjs

I'm trying to add a new record to the database using REST API.
The DELETE and GET methods work just fine, but I can't figure out what's wrong with the POST method.
My API Controller:
[HttpPost] // POST: api/Contacts //to add image as param?
public void InsertNewContact([FromBody]Contact Contact)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConStr"].ConnectionString);
SqlCommand cmd = new SqlCommand(#"INSERT INTO Contacts(Name,Phone,Mail,City,Address) VALUES(#Name, #Phone,#Mail,#City,#Address)", con);
SqlParameter Name = new SqlParameter("#Name", Contact.Name);
cmd.Parameters.Add(Name);
SqlParameter Phone = new SqlParameter("#Phone", Contact.Phone);
cmd.Parameters.Add(Phone);
SqlParameter Mail = new SqlParameter("#Mail", Contact.Mail);
cmd.Parameters.Add(Mail);
SqlParameter City = new SqlParameter("#City", Contact.City);
cmd.Parameters.Add(City);
SqlParameter Address = new SqlParameter("#Address", Contact.Address);
cmd.Parameters.Add(Address);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
}
finally
{
con.Close();
}
}
HTTP POST request in HTML:
$scope.add_to_db = function ()
{
//insert contact to db
$http.post(url + "/api/Contacts",
JSON.stringify({ Name: $scope.contactName, Phone: $scope.contactPhone, Mail: $scope.contactMail, City: $scope.contactCity, Address: $scope.contactAddress}))
.then(function (res) {
$state.go("contacts");
}, function (err) { alert(err); });
}
The response is returned to the success function but nothing's changed in the database. What could be the problem here?
Catch Block is Empty to know the error, Usually i go through these scenarios and i make sure the following are implemented in the code to track down the failure reason:
1) #RequestBody in API controller should be accepting Contact model
data.
2) Check if JSON object created at angular is in sync with Contact model/ POJO.
3) Use POSTMAN to debug only REST API initially, which can help you to track down failure.

Set parameters with HTTP POST in Apex

I'm trying to set POST content using Apex. The example below sets the variables using GET
PageReference newPage = Page.SOMEPAGE;
SOMEPAGE.getParameters().put('id', someID);
SOMEPAGE.getParameters().put('text', content);
Is there any way for me to set the HTTP type as POST?
Yes but you need to use HttpRequest class.
String endpoint = 'http://www.example.com/service';
String body = 'fname=firstname&lname=lastname&age=34';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setbody(body);
Http http = new Http();
HTTPResponse response = http.send(req);
For additional information refer to Salesforce documentation.
The following apex class example will allow you to set parameters in the query string for a post request -
#RestResource(urlmapping = '/sendComment/*')
global without sharing class postComment {
#HttpPost
global static void postComment(){
//create parameters
string commentTitle = RestContext.request.params.get('commentTitle');
string textBody = RestContext.request.params.get('textBody');
//equate the parameters with the respective fields of the new record
Comment__c thisComment = new Comment__c(
Title__c = commentTitle,
TextBody__c = textBody,
);
insert thisComment;
RestContext.response.responseBody = blob.valueOf('[{"Comment Id":
'+JSON.serialize(thisComment.Id)+', "Message" : "Comment submitted
successfully"}]');
}
}
The URL for the above API class will look like -
/services/apexrest/sendComment?commentTitle=Sample title&textBody=This is a comment

Javamail Configuration clarification

Through my application using Javamail API if I want to send email between any two external email addresses say gmail->yahoo or yahoo->gmail or any other email account without using authentication mechanism how should I configure mail.smtp.host property?
What is the correct way of configuring javamail properties for sending emails between any two external email addresses ?
Sample code to send mail is given below:
Session session = Session.getDefaultInstance(new Properties(),null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("test#gmail.com"));
InternetAddress[] toAddress = {new InternetAddress("test#yahoo.com")};
message.setRecipients(Message.RecipientType.TO, toAddress);
message.setSubject("test mail"); message.setText("test body");
Transport.send(message);
Most public mail servers require authentication. If you want to do it without authentication, you'll need to run your own mail server.
This is for gmail, try it. You need mail.jar
public static void main(String[] args) {
final String username = "yourId#gmail.com";
final String password = "your-pwd";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("yourId#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("some-mail#gmail.com"));
message.setSubject("A Mail Subject");
message.setText("Hey I'm sending mail using java api");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Edit :
Link to download Java mail Api along with mail.jar

Trying to access google places using google api client in GAE

I am trying to access google places api from appengine using code like this:
String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json";
// setup up the HTTP transport
HttpTransport transport = new UrlFetchTransport();
// add default headers
GoogleHeaders defaultHeaders = new GoogleHeaders();
transport.defaultHeaders = defaultHeaders;
transport.defaultHeaders.put("Content-Type", "application/json");
JsonHttpParser parser = new JsonHttpParser();
parser.jsonFactory = new JacksonFactory();
transport.addParser(parser);
// build the HTTP GET request and URL
HttpRequest request = transport.buildGetRequest();
request.setUrl(PLACES_DETAILS_URL);
GenericData data = new GenericData();
data.put("reference", restaurantGoogleId);
data.put("sensor", "false");
data.put("key", ApplicationConstants.GoogleApiKey);
JsonHttpContent content = new JsonHttpContent();
content.jsonFactory=new JacksonFactory();
content.data = data;
request.content = content;
try {
HttpResponse response = request.execute();
String r = response.parseAsString();
r=r;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I don't know even if this is the recommended way. If so, why this doesn't work?If I put a request in the browser directly it works, but with this code it always returns me "Request Denied".
Thanks in advance.
At the end it was easy, I mixed get and post verbs:
HttpTransport transport = new UrlFetchTransport();
// add default headers
GoogleHeaders defaultHeaders = new GoogleHeaders();
transport.defaultHeaders = defaultHeaders;
transport.defaultHeaders.put("Content-Type", "application/json");
JsonCParser parser = new JsonCParser();
parser.jsonFactory = new JacksonFactory();
transport.addParser(parser);
// build the HTTP GET request and URL
HttpRequest request = transport.buildGetRequest();
request.setUrl("https://maps.googleapis.com/maps/api/place/details/json?reference=CmRYAAAAciqGsTRX1mXRvuXSH2ErwW-jCINE1aLiwP64MCWDN5vkXvXoQGPKldMfmdGyqWSpm7BEYCgDm-iv7Kc2PF7QA7brMAwBbAcqMr5i1f4PwTpaovIZjysCEZTry8Ez30wpEhCNCXpynextCld2EBsDkRKsGhSLayuRyFsex6JA6NPh9dyupoTH3g&sensor=true&key=<APIKEY>");
try {
HttpResponse response = request.execute();
String r = response.parseAsString();

Resources