I have an Ionic app and contact form page (with Name, Email, and Phone).
After the user clicks the Submit button, I want this form data to be sent to my E-mail. How do I do this?
You'd need to setup some kind of REST api, so that when the user clicks on the submit button, the data in the contact form is sent to the REST api you've set up, which will trigger it to send an email to you with the contents of the user's message.
Since you've tagged this with Node.JS, I would suggest that you have the contact form's action be send to something like 'http://yoursite.com/sendemail/' and then your API would handle the call with something like:
router.route('/sendemail/')
.post(function(req, res) {
var userInput = req.body;
var message = {
text: userInput.message,
from: userInput.name + ' <' + userInput.email + '>',
to: 'youremail#email.com',
subject: userInput.subject,
attachment:
[
{data: this.text, alternative:true},
]
};
server.send(message, function(err, message) {
if(err) {
res.status(400);
console.log(err);
} else {
res.status(200)
}
});
});
(you'll need to change some variables to fit your code)
Hope this helps!
Related
What I want to do, is have a user dynamically create an image, like a nametag and then I want to save the image to the server as a pdf, then send the pdf via emil, to myself or someone else.
So far, I am able to dynamically create the nametag, and I am able to send an email when a button is pressed. Now what I can't seem to find is how to save the element as a pdf.
My code:
The endpoint that handles sending the email
let cors = require('cors');
let express = require('express');
let app = express();
app.use(cors());
let nodemailer = require('nodemailer');
/**
*
* Function to hopefully send an email :)
*/
app.post("/sendMail", function (req, res) {
console.log(req);
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'user#gmail.com',
pass: 'Password'
}
});
let mailOptions = {
from: 'user#gmail.com',
to: 'recipient#alphagraphics.com',
subject: 'Test',
text: 'It works!'
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
});
app.listen(8080);
The javascript that handles the button click to send the email
$('#some-long-stupid-unique-name').click(function(){
$.ajax({
type: 'POST',
url: 'http://192.168.1.23:8080/sendMail'
});
});
The html before editing
<div>
<div id="name"></div>
<div id="title></div>
</div>
Now the user will have some text boxees they cna type into and when they click "Update" whatever they typed into the text boxes (respectivly named Name and Title) the html will look like the following
<div>
<div id="name">My Name Here></div>
<div id="title">My Title Here</div>
</div>
How can I turn this element into a pdf and save it to my server, so I can then send it over from my mailing client?
Edit: I have seen other posts on how to "Save as pdf" but it seemed to me that they all save to the clients machine, but for me and the clients, it doesn't matter so much if they can save it on their machine, it is more important to save it to the server
Edit: Note that the format (pdf) doesn't matter so much I just thought it would be the easiest and most versatile?
If you would only save it as png, I would just say you to create a foreignObject inside an svg and render it on canvas, but since you want to convert that to pdf, I will do something that I rarely like doing. Try jsPDF, it should come in handy:
https://parall.ax/products/jspdf
I'm using Direct Line 3.0 and the Microsoft Bot Framework and require the webpage to send some form fields to the bot as if the user sent them. For example when the user presses Submit, the fields email, phone etc are sent to the bot as if the user sent them like this: email, phone, etc.
This is because the bot redirects the user depending on what the values are. The bot is in C# and is hosted on Azure. The logic for submitting the information should be in JavaScript.
Bot is initiated like this:
<div id="chat" style="background-color:white;
width:250px;height:600px;"><div id="bot" />
<script src="https://cdn.botframework.com/botframework-
webchat/latest/botchat.js"></script></div></div>
and through a DirectLine script:
<script>
const botConnection = new BotChat.DirectLine({
secret: 'secret',
});
BotChat.App({
user: { id: 'You' },
bot: { id: 'myId' },
resize: 'detect',
botConnection: botConnection
}, document.getElementById("bot"));
</script>
All I need is to send one string as if the user sent it. I cannot do this with HTML manipulation it seems.
Thanks for anyone pointing me in the right direction!
Sending a message to the bot "like the user would do" is possible using the "Backchannel" functionnality of the webchat.
There is a good sample of use in the Readme file on Github webchat's page: https://github.com/Microsoft/BotFramework-WebChat#the-backchannel.
You have to use your botConnection previously created to send an activity like the following:
botConnection.postActivity({
from: { id: 'me' },
name: 'buttonClicked',
type: 'event',
value: ''
});
Then catch this on your bot code, but checking the Activity type which will be Event in this case.
You can have a look on how they throw this postActivity from a button click in the sample provided: samples here: https://github.com/Microsoft/BotFramework-WebChat/blob/master/samples/backchannel/index.html
Or in this other sample that I made (available on Github, both client web page and bot code): the bot's controller looks like the following:
[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// POST: api/Messages
/// Receive a message from a user and reply to it
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
// Process each activity
if (activity.Type == ActivityTypes.Message)
{
await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
}
// Webchat: getting an "event" activity for our js code
else if (activity.Type == ActivityTypes.Event && activity.ChannelId == "webchat")
{
var receivedEvent = activity.AsEventActivity();
if ("localeSelectionEvent".Equals(receivedEvent.Name, StringComparison.InvariantCultureIgnoreCase))
{
await EchoLocaleAsync(activity, activity.Locale);
}
}
// Sample for Skype: locale is provided in ContactRelationUpdate event
else if (activity.Type == ActivityTypes.ContactRelationUpdate && activity.ChannelId == "skype")
{
await EchoLocaleAsync(activity, activity.Entities[0].Properties["locale"].ToString());
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
private async Task EchoLocaleAsync(Activity activity, string inputLocale)
{
Activity reply = activity.CreateReply($"User locale is {inputLocale}, you should use this language for further treatment");
var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
await connector.Conversations.SendToConversationAsync(reply);
}
}
I'm creating an app in nodejs to send an email using MailChimp. I've tried to use https://apidocs.mailchimp.com/sts/1.0/sendemail.func.php but changed it to use 3.0 api because 1.0 seems to no longer work (big surprise). I've setup my app with
var apiKey = '<<apiKey>>',
toEmail = '<<emailAddress>>',
toNames = '<<myName>>',
message = {
'html': 'Yo, this is the <b>html</b> portion',
'text': 'Yo, this is the *text* portion',
'subject': 'This is the subject',
'from_name': 'Me!',
'from_email': '',
'to_email': toEmail,
'to_name': toNames
},
tags = ['HelloWorld'],
params = {
'apikey': apiKey,
'message': message,
'track_opens': true,
'track_clicks': false,
'tags': tags
},
url = 'https://us13.api.mailchimp.com/3.0/SendEmail';
needle.post(url, params, function(err, headers) {
if (err) {
console.error(err);
}
console.log(headers);
}
});
I keep getting a 401 response (not authorized because I'm not sending the API key properly)
I have to use needle due to the constraints on the server.
There is no "SendEmail" endpoint in API v3.0. MailChimp's STS was a pre-cursor to its Mandrill transactional service and may only still work for user accounts that have existing STS campaigns. No new STS campaigns can be created. If you have a monthly, paid MailChimp account, you should look into Mandrill. If not, I've had good luck with Mailgun.
You should use HTTP Basic authentication in MailChimp API 3.0.
needle.get('https://<dc>.api.mailchimp.com/3.0/<endpoint>', { username: 'anystring', password: 'your_apikey' },
function(err, resp) {
// your code here...
});
EDIT
#TooMuchPete is right, the SendMail endpoint is not valid in MailChimp API v3.0. I didn't notice that and I've edited my answer.
Can someone please provide the correct method to send an email verification upon user creation? This is the important part...
a) I would like the user to have immediate access upon signing up. But if the user has not yet clicked clicked on the verification link within 48 hours, I would like to deny them logging in until they have clicked on the link.
My code so far sends an email verification but the user has continuos access to the application with or without clicking on the verification link (so my code is of course incomplete).
client.js
Template.join.events({
'submit #join-form': function(e,t){
e.preventDefault();
var firstName= t.find('#join-firstName').value,
lastName= t.find('#join-lastName').value,
email = t.find('#join-email').value,
password = t.find('#join-password').value,
username = firstName.substring(0) + '.' + lastName.substring(0),
profile = {
fullname: firstName + ' ' + lastName
};
Accounts.createUser({
email: email,
username: username,
password: password,
userType: // 'reader' or 'publisher'
createdAt: new Date(),
profile: profile
}, function(error) {
if (error) {
alert(error);
} else {
Router.go('home');
}
});
}
});
server.js
Meteor.startup(function () {
process.env.MAIL_URL = 'smtp://postmaster.....';
Accounts.emailTemplates.from = "no-reply#mydomain.com";
Accounts.emailTemplates.sitename = "My SIte Name";
Accounts.emailTemplates.verifyEmail.subject = function(user) {
return 'Please confirm tour Email address' ;
},
Accounts.emailTemplates.verifyEmail.text = function(user, url) {
return 'Click on the link below to verify your address: ' + url;
}
Accounts.config({
sendVerificationEmail: true
});
My attempt have been made through own readings on meteor docs and looking at other code on SO. I am stuck guys. Thanks for the support.
I think the basic idea is to have some validation code eg in Accounts.validateLoginAttempt which you want to check every time before user logs in. What you can do is to store the date&time when user signs up in user.profile.joinDate. If a user tries to login
Check if the email address has been verified or
check if the user is logging within the grace period of 48 hrs
isWithinGracePeriod = function(user) {
** TBD returning true or false.
This can be tricky when you
have multiple instances in
different time-zones.
** }
and
Accounts.validateLoginAttempt(function(attempt){
if (attempt.user && attempt.user.emails && !attempt.user.emails[0].verified ) {
console.log('No verification action received yet.');
return isWithinGracePeriod(attempt.user);
}
return true;
});
Further, here is the HTML/spacebars stuff:
<body>
{{ > start }}
</body>
<template name="start">
{{#if currentUser}}{{>showUserProfile}}{{else}}{{> login}}{{/if}}
</template>
<template name="login">
## Grab username/password here
</template>
If the login template is created, we can try to capture the verification code after the user clicked the verification link. Note that, if no user is logged in, then login will be rendered, so we attach to login via
Template.login.created = function() {
if (Accounts._verifyEmailToken) {
Accounts.verifyEmail(Accounts._verifyEmailToken, function(err) {
if (err != null) {
if (err.message = 'Verify email link expired [403]') {
var message ='Sorry this verification link has expired.';
console.log(message);
alertBox = Blaze.renderWithData(Template.Alert, {message: message}, $("body").get(0));
}
} else {
var message = "Thank you! Your email address has been confirmed.";
console.log(message);
alertBox = Blaze.renderWithData(Template.Alert, {message: message}, $("body").get(0));
}
});
}
};
The verification link is send in "hook" to Accounts.createUser:
Accounts.onCreateUser(function(options, user) {
user.profile = {};
Meteor.setTimeout(function() {
Accounts.sendVerificationEmail(user._id);
}, 2 * 3000);
return user;
});
I'm attempting to use the Facebook Javascript SDK to post to an authenticated user's friend's wall. I get what appears to be a valid post ID in the response but the post does not appear on Facebook, and when I use the FB Graph API explorer to view the post, it simply returns false.
I'm using the FB login button with "publish_stream" permission for authentication and have a test FB app set up to get a valid App ID. I'm using the following code to post to the user's friend's wall:
FB.api('/[USER_ID]/feed', 'post', {
message: 'Testing the Facebook JavaScript API',
link: 'http://developers.facebook.com'
}, function(response) {
if (!response || response.error) {
console.log('Error occured');
} else {
console.log('Post ID: ' + response.id);
console.dir(response);
}
});
It works as expected when I replace [USER_ID] with 'me' - I can see the post on my FB timeline. However, when I use one of my friends' user IDs, I get a post ID response, but the post does not appear anywhere on their feed. Thoughts?
Here's my login button, too:
<fb:login-button show-faces="false" width="200" scope="publish_stream,publish_actions" perms="publish_stream"></fb:login-button>
I had the same problem. I worked on it like crazy for 5 hours. And actually, I think there is no problem. The only thing is that the posts on other's walls can arrive few hours later.
If anyone has the same problem, at least wait for a few hours before completely changing your code and turning crazy.
You can't post to a friend's wall
I was able to resolve this issue by creating an entirely new FB App from scratch, after which point the above code worked, which led me to think the issue must be in the configuration of my previous Facebook app. The only major difference I found was in App > Settings > Basic > Website > Site URL, I had entered the domain for my app and not the full path to the app page itself. So, you can indeed dynamically publish a post to the authenticated user's friend's wall.
here is with javascript sdk and facebbok c# sdk:
function fb_publish() {
FB.ui(
{
method: 'stream.publish',
message: 'Message here.',
attachment: {
name: 'Name here',
caption: 'Caption here.',
description: (
'description here'
),
href: 'url here'
},
action_links: [
{ text: 'Code', href: 'action url here' }
],
user_prompt_message: 'Personal message here'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
and
var client = new FacebookClient("my_access_token");
dynamic parameters = new ExpandoObject();
parameters.message = "Check out this funny article";
parameters.link = "http://www.example.com/article.html";
parameters.picture = "http://www.example.com/article-thumbnail.jpg";
parameters.name = "Article Title";
parameters.caption = "Caption for the link";
parameters.description = "Longer description of the link";
parameters.actions = new {
name = "View on Zombo",
link = "http://www.zombo.com",
};
parameters.privacy = new {
value = "ALL_FRIENDS",
};
parameters.targeting = new {
countries = "US",
regions = "6,53",
locales = "6",
};
dynamic result = client.Post("me/feed", parameters);
and would you please mark it as answered if it helps :)