How to send mail automatically in ng-click? - angularjs

I'm using angularjs 1.4.8 in Visual Studio 2013. I want to send email to xxxx# xxxx.com with message "Your registration completed" automatically after button has been clicked. How can I send email by angularjs?
[HttpPut]
[Route("api/SendMail")]
protected void sendmail()
{
var fromAddress = "xxxk#xxxxx.com";
var toAddress = "rrrr#rrr.com";
const string fromPassword = "workufs1234";
MailMessage mailMessage = new MailMessage(fromAddress, toAddress);
mailMessage.To.Add(toAddress);
mailMessage.Subject = "Documents";
string messge = "hellooooo";
string tempmsg = "";
var messg = #"<html><body><br />Dear ss ,<br /><br /> <br />";
mailMessage.To.Add(toAddress);
string html = messg.ToString();
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
MailMessage mail = new MailMessage();
mailMessage.AlternateViews.Add(altView);
mailMessage.Body = messg.ToString();
mailMessage.IsBodyHtml = true;
SmtpClient mailSender = new SmtpClient("162.222.225.82"); //use this if you are in the development server
mailSender.Host = "smtp.gmail.com";
mailSender.Port = 587;
mailSender.EnableSsl = true;
mailSender.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
mailSender.Credentials = new NetworkCredential(fromAddress, fromPassword);
mailSender.Timeout = 40000;
mailSender.Send(mailMessage);
}
How can test this using postman. is this httppost or put or?

HTML code:
<button ng-click="sendMail()"></button>
Controller:
$scope.message = {} // contact info goes here
$scope.sendMail = function(){
var mail = 'mailto:mohamed#labouardy.com?subject=' + $scope.message.name +
'&body=' + $scope.message.content;
$window.open(mail);
}

I think you will need a server side to do this properly. (PHP / NodeJS, ...)
On my NodeJS server, I'm using 'nodemailer', which works perfectly.
https://www.npmjs.com/package/nodemailer
Hope it helps.

Related

How do i filter using a partial VM name (string) in vmware vSphere client REST API?

Good day!
i am trying to automate some actions to be done to VM's in my organisation.
The action to be done depends on the a substring in the VM name.
for eg, i would need to delete all VM's whose name starts with 'delete', etc.
I can use the below API to fetch the list of VM's:
GET https://{{vc}}/rest/vcenter/vm
However, this API can only fetch a maximum of 1000 VM's.
Is there any way i can filter and get only the list of VM's with the expected substring from this API?
from what i understand, appending filter.names.1 to the above API works but for that i need to input the exact and entire VM name.
is there a way where i can search for a list of VM's with partial text?
Apologies, i am a newbie to this.
thank you for your time!
Since vSphere API does not provide such capability to search by partial VM name there is a tricky way to do this.
I am using the search functionality in vSphere Client 6.7.0.
Prerequisite is to get the following cookies first:
VSPHERE-USERNAME
VSPHERE-CLIENT-SESSION-INDEX
VSPHERE-UI-JSESSIONID
You have to do three calls in order to get them:
1. GET "https://[URL]/ui/login" you will be forwarded to a new URL from where you can take "SAMLRequest token"
2. POST "https://[URL]/websso/SAML2/SSO/vsphere.local?SAMLRequest=[SAMLRequest token]", set as header "CastleAuthorization=Basic%20[credentials]" where credentials is the Base64 encoding of "User:Password". Get the value of "SAMLResponse" hidden field from the response.
3. POST "https://[URL]/ui/saml/websso/sso", set "SAMLResponse=[SAMLResponse value]", where "SAMLResponse value" you have it from the previous response. From this response you will get the cookies.
Once you have those three cookies, make a new call as you set the cookies
4. GET "https://[URL]/ui/search/quicksearch/?opId=0&query=[partial VM name]"
For example for this call "https://[URL]/ui/search/quicksearch/?opId=0&query=test"
you will get response like this:
[{
"icon": "vsphere-icon-vm",
"labelPlural": "Virtual Machines",
"label": "Virtual Machine",
"results": [{
"id": "urn:vmomi:VirtualMachine:vm-2153:103ac083-e314-47ea-942a-c685d9a4e6c9",
"type": "VirtualMachine",
"name": "TestVM1"
}, {
"id": "urn:vmomi:VirtualMachine:vm-3391:103ac083-e314-47ea-942a-c685d9a4e6c9",
"type": "VirtualMachine",
"name": "TestVM2"
}, {
"id": "urn:vmomi:VirtualMachine:vm-3438:103ac083-e314-47ea-942a-c685d9a4e6c9",
"type": "VirtualMachine",
"name": "TestVM3"
}
]
}
]
Below is my own vSphere Search Proxy Client written in C#:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace VsphereSearchProxy
{
static class Program
{
const string VSPHERE_URL = "VSPHERE_URL";
static string VSPHERE_CRED_BASE64
{
get
{
var plainTextCred = Encoding.UTF8.GetBytes("USER:PASS");
return Convert.ToBase64String(plainTextCred);
}
}
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Expected one argument: Virtual Machine name");
return;
}
var vmName = args[0];
var vsphereUri = VSPHERE_URL.TrimEnd('/');
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.Expect100Continue = true;
//=================================================================
Console.WriteLine("\nStep 1\n");
var url1 = vsphereUri + "/ui/login";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
request.Method = "GET";
request.KeepAlive = true;
request.AllowAutoRedirect = true;
var response = (HttpWebResponse)request.GetResponse();
var url2 = response.ResponseUri.AbsoluteUri;
Console.WriteLine("url2: " + url2);
WebHeaderCollection headerCollection = response.Headers;
Console.WriteLine("\nResponse headers\n");
for (int i = 0; i < headerCollection.Count; i++)
{
Console.WriteLine("\t" + headerCollection.GetKey(i) + " = " + headerCollection.Get(i));
}
//=================================================================
Console.WriteLine("\nStep 2\n");
request = (HttpWebRequest)WebRequest.Create(url2);
request.Method = "POST";
request.Headers.Add("Authorization: Basic " + VSPHERE_CRED_BASE64);
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
request.AllowAutoRedirect = false;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write("CastleAuthorization=Basic%20" + VSPHERE_CRED_BASE64);
streamWriter.Flush();
streamWriter.Close();
}
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Expected 200 OK, but got " + response.StatusCode);
}
headerCollection = response.Headers;
Console.WriteLine("\nResponse headers\n");
for (int i = 0; i < headerCollection.Count; i++)
{
Console.WriteLine("\t" + headerCollection.GetKey(i) + " = " + headerCollection.Get(i));
}
var responseString = "";
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
responseString = reader.ReadToEnd();
}
var SAMLResponse = "";
Match match = Regex.Match(responseString, "<input[^>]*type=\"hidden\"\\s+name=\"SAMLResponse\"[^>]*value=\"([^\"]*)\"");
if (match.Success)
{
SAMLResponse = match.Groups[1].Value;
SAMLResponse = SAMLResponse.Replace("\n", "");
//Console.WriteLine("SAMLResponse: " + SAMLResponse);
}
if (string.IsNullOrWhiteSpace(SAMLResponse))
{
throw new Exception("SAMLResponse is missing or blank");
}
//=================================================================
Console.WriteLine("\nStep 3\n");
var url3 = vsphereUri + "/ui/saml/websso/sso";
request = (HttpWebRequest)WebRequest.Create(url3);
request.Method = "POST";
request.Headers.Add("Authorization: Basic " + VSPHERE_CRED_BASE64);
request.ContentType = "application/x-www-form-urlencoded";
request.KeepAlive = true;
request.AllowAutoRedirect = false;
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write("SAMLResponse=" + HttpUtility.UrlEncode(SAMLResponse));
streamWriter.Flush();
streamWriter.Close();
}
response = (HttpWebResponse)request.GetResponse();
var cookies = response.Headers["Set-Cookie"];
Console.WriteLine("cookies: " + cookies);
headerCollection = response.Headers;
Console.WriteLine("\nResponse headers\n");
for (int i = 0; i < headerCollection.Count; i++)
{
Console.WriteLine("\t" + headerCollection.GetKey(i) + " = " + headerCollection.Get(i));
}
//=================================================================
Console.WriteLine("\nStep 4\n");
var url4 = vsphereUri + "/ui/search/quicksearch/?opId=:1&query=" + vmName;
request = (HttpWebRequest)WebRequest.Create(url4);
request.Method = "GET";
request.Headers.Add("Cookie: " + cookies);
request.KeepAlive = true;
request.AllowAutoRedirect = false;
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Expected 200 OK, but got " + response.StatusCode);
}
var jsonResp = "";
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
jsonResp = reader.ReadToEnd();
}
Console.WriteLine(jsonResp);
}
}
}
Unfortunately the vSphere Automation API isn't setup to filter on partial names or even when using a wildcard. Some of the available filters may help you limit the output to be under the 1000 object limit (example: filter on specific clusters and/or folders).
Hopefully this is something that's added in a future release.

Relate a Docusign Envelope to a Salesforce Custom object

I have a Template created in DS which contains custom tags which are mapped to Salesforce fields. The template works well when used via the JS button example code provided by DS and the fields appear as expected.
I am now trying to automate the process using the Docusign SOAPAPI. When creating the envelope the custom fields aren't populated; even the signer fields.
Below is my code:-
DocusignAPI.ArrayOfRecipient1 recipients = new DocusignAPI.ArrayOfRecipient1();
recipients.Recipient = new list<DocusignAPI.Recipient>();
DocusignAPI.Recipient recipient = new DocusignAPI.Recipient();
recipient.Email = signer_email;
recipient.UserName = signer_name;
recipient.ID = 1;
recipient.Type_x = 'Signer';
recipient.RoutingOrder = 1;
recipients.Recipient.add(recipient);
DocusignAPI.ArrayOfTemplateReference templateReferences = new DocusignAPI.ArrayOfTemplateReference();
templateReferences.TemplateReference = new list<DocusignAPI.TemplateReference>();
DocusignAPI.TemplateReference templateReference = new DocusignAPI.TemplateReference();
TemplateReference.Template = '6bc2930f-6d46-4804-a9fc-69d1cf3ebe09';
templateReference.TemplateLocation = 'Server';
templateReferences.TemplateReference.add(templateReference);
DocusignAPI.EnvelopeInformation ei = new DocusignAPI.EnvelopeInformation();
ei.AccountId = account_id;
ei.Subject = 'Lorem Ipsum';
ei.EmailBlurb = 'More text...';
// Create an envelope and fill it in
DocusignAPI.CustomField field = new DocusignAPI.CustomField ();
field.Name = 'DSFSSourceObjectId';
field.Value = 'a1qW0000000vMCj';
field.Show = 'false';
field.CustomFieldType = 'Text';
DocusignAPI.ArrayOfCustomField arrayOfCustomFields = new DocusignAPI.ArrayOfCustomField();
arrayOfCustomFields.CustomField = new list<DocusignAPI.CustomField>();
arrayOfCustomFields.CustomField.add(field);
ei.CustomFields = arrayOfCustomFields;
try {
DocusignAPI.EnvelopeStatus result = api_sender.CreateEnvelopeFromTemplates(templateReferences, recipients, ei, true);
envelope_id = result.EnvelopeID;
System.debug('Returned successfully, envelope_id = ' + envelope_id );
} catch ( CalloutException e) {
System.debug('Exception - ' + e );
error_code = 'Problem: ' + e;
error_message = error_code;
}
All customtags are related to my custom object with id defined in the CustomField above.
Any help gratefully appreciated.
Turns out I need to add in the object API name to the Id. Solution is:-
DocusignAPI.CustomField field = new DocusignAPI.CustomField ();
field.Name = 'DSFSSourceObjectId';
field.Value = 'a1qW0000000vMCj~Property__c';
field.Show = 'false';
field.CustomFieldType = 'Text';

GMAIL API sending email with attachment in c#

I need help with sending email w/attachment using Gmail Api in c#.
I have read Google website on sending emails with attachment but the example is in java.
Its too late for the answer, but posting it in case anyone needs it:)
Need MimeKit library for this: can be installed from NuGet.
Code:
public void SendHTMLmessage()
{
//Create Message
MailMessage mail = new MailMessage();
mail.Subject = "Subject!";
mail.Body = "This is <b><i>body</i></b> of message";
mail.From = new MailAddress("fromemailaddress#gmail.com");
mail.IsBodyHtml = true;
string attImg = "C:\\Documents\\Images\\Tulips.jpg OR Any Path to attachment";
mail.Attachments.Add(new Attachment(attImg));
mail.To.Add(new MailAddress("toemailaddress.com.au"));
MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
Message message = new Message();
message.Raw = Base64UrlEncode(mimeMessage.ToString());
//Gmail API credentials
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scope,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
//Send Email
var result = service.Users.Messages.Send(message, "me/OR UserId/EmailAddress").Execute();
}
Scope can be:
GmailSend or GmailModify
static string[] Scope = { GmailService.Scope.GmailSend };
static string[] Scope = { GmailService.Scope.GmailModify };
Base64UrlEncode function:
private string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}
I have an example in VB.net. GMail API Emails Bouncing.
Google page provides examples in Java and Python only. The objects being used in the Java example are not available in .Net version of API. It is not possible to translate those examples.
Fortunately, it is quite easy to do the same in C#/VB. Just use plain old Net.Mail.MailMessage to create a message including attachments, then use MimeKit (NuGet it) to convert the message into string and pass the string (after encoding Base64) to "Raw" field of message.send of Gmail API.
There's nothing particular to sending an attachment with the Gmail API. Either way the Gmail API message.send() takes a full RFC822 email message in the message.raw field (urlsafe base64 encoded). The main trick is building up such an RFC822 email message string in your language. I imagine there are some MIME message librarys in C# and that's the main issue is finding those libraries. I don't do C# but javax.internet.mail.MimeMessage works well in java and the 'email' module is good for python.
This other post seems relevant:
How to send multi-part MIME messages in c#?
string[] Scopes = { GmailService.Scope.GmailSend };
string ApplicationName = "Gmail API App";
public GmailForm()
{
InitializeComponent();
SendHTMLmessage();
}
string Base64UrlEncode(string input)
{
var data = Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(data).Replace("+", "-").Replace("/", "_").Replace("=", "");
}
public void SendHTMLmessage()
{
//Create Message
MailMessage mail = new MailMessage();
mail.Subject = "Subject!";
mail.Body = "This is <b><i>body</i></b> of message";
mail.From = new MailAddress("youremail#gmail.com");
mail.IsBodyHtml = true;
string attImg = "C:\\attachment.pdf";
mail.Attachments.Add(new Attachment(attImg));
mail.To.Add(new MailAddress("receiver#mail.com"));
MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
var msg = new Google.Apis.Gmail.v1.Data.Message();
msg.Raw = Base64UrlEncode(mimeMessage.ToString());
//Gmail API credentials
UserCredential credential;
using (var stream =new FileStream(Application.StartupPath + #"/credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart2.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,Scopes,"user",CancellationToken.None,new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
//Send Email
var result = service.Users.Messages.Send(msg, "me").Execute();
MessageBox.Show("Your email has been successfully sent !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

Post data to web API

I've been trying to send data to a web API VIA post. But it doesn't seem to be sending it.
Here's how I do it.
var baseAddress = "http://192.168.0.103/vchatapi/api/Images?gsmNumber=" + profileNumberLbl.Content + "&content=" + base64 + "&contentType=image/" + contentType;
var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";
This code works with get:
var baseAddress = "http://192.168.0.103/vchatapi/api/SendSMSVerificationCode?gsmNumber=" + areCode + mobile + "&udid=123456";
var http = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new System.Uri(baseAddress));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "GET";
try
{
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
verificationCode = verificationCode.FromJson(content);
if (!verificationCode.Equals(""))
{
MessageBox.Show(this, "Verification Code: " + verificationCode);
verificationTextBox.IsEnabled = true;
areaCodeCB.IsEnabled = false;
mobileNumberTB.IsEnabled = false;
}
else
{
MessageBox.Show(this, "Invalid Number");
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message);
}
Any ideas? Thanks!
Since you are doing a POST, you would be sending the content in the body of the request. You would need to get hold of the request's stream and write data to it. The following answer post has a very concise example:
https://stackoverflow.com/a/2551006/1184056

Missing credential from request in OOB application

I'm writing a simple Silverlight application in which I have the following code, which I think is pretty standard:
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
var request = new WebClient();
var cred = new NetworkCredential(Server.UserName, Server.Password);
request.Credentials = cred;
request.UseDefaultCredentials = false;
request.DownloadStringCompleted += TestServerCompleted;
var uri = new Uri(Server.GetRequestUrl(Methods.ping));
request.DownloadStringAsync(uri);
Yet when I view the request in Fiddler, no credentials are added to the headers. What am I missing? Shouldn't there be an "Authorization: Basic ..." header in there?
Try with something like this.
HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.UseDefaultCredentials = false;
req.Credentials = ew NetworkCredential(Server.UserName, Server.Passwor
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
return req;
req.BeginGetResponse((IAsyncResult asynchronousResultResponse) =>
{
try
{
HttpWebRequest requestResponse = (HttpWebRequest)asynchronousResultResponse.AsyncState;
HttpWebResponse response = (HttpWebResponse)requestResponse.EndGetResponse(asynchronousResultResponse);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
//Your response is here in responseString
streamResponse.Close();
streamRead.Close();
response.Close();
}
catch (Exception e)
{
Callback(null, e);
}
}, webRequest);
I Hope it can help, even 2 months later...

Resources