I want to send an email using a template. I want to have a GSP file where i could style it, and send the email. Currently the send mail function is as follows:
def sendEmail(){
mailService.sendMail {
to "email","**email**"
from "email"
subject "Hi"
body 'Hi'
}
}
in my config.groovy file
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "email"
password = "pwd"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}
I went through another Stack Overflow post on this: Where should i add the mail templates ? is it in the views folder ?
sendMail{
multipart true
to "[hidden email]"
subject "Subject goes here"
html g.render( template: '/emails/mailTemplate')
inline 'springsourceInlineImage', 'image/jpg', new File('./web-app/images/springsource.png')
}
UPDATE
I TREID ADDING A mailTemplate.gsp UNDER EMAILS/ BUT IT DIDNT WORK.
ERROR I GOT Template not found for name [/emails/mailTemplate] and path [/emails/_mailTemplate.gsp]
You can use groovyPageRenderer.render() to parse your email. Below, an example:
class MailingService {
def groovyPageRenderer
def mailService
def yourFunction(User user) {
def content = groovyPageRenderer.render(view: '/mails/myTemplate')
mailService.sendMail {
to user.email
from "email#test.com"
subject "MySubject"
html(content)
}
}
}
In this case, the template is here: /views/mails/MyTemplateFile.gsp
Hope this helps.
Edit:
And the render could be used with a model. Example:
groovyPageRenderer.render(view:'/mails/myTemplate',model:[user:user])
Edit2:
I forgot to add the mailService in my first reply
well, you can try this code...
mailService.sendMail {
to user.email
from "email#test.com"
subject "MySubject"
body(view:'/emails/mailTemplate', model: [a:A])
}
here mailTemplate.gsp is in view/emails. In body of mail service you can use render syntax.
then add '<%# page contentType="text/html" %>' in top of mailTemplate.gsp
Well looking at your code, everything looks good enough.
html g.render(template : '/path/to/template')
should render your template and it will become the body of your mail message.
Have you made sure that you made your template as _template. Since all the gsp's that start with (_) are only considered as a template.
You should also make all the styling(css) inline so that it gets rendered without errors in all mail providers.
Related
I am wondering what is the correct way of sending HTML templates with ktor via email.
This answer Sending Emails From Ktor Application can help inline HTML, or simple string but not hbs or other templates which can be used in ktor.
email service will work, but I do want to use a template. And doing it via MustacheContent will not work
package com.meet.utils.email
import com.meet.utils.Constants
import org.apache.commons.mail.DefaultAuthenticator
import org.apache.commons.mail.HtmlEmail
fun sendForgotPasswordEmail(token: String, emailTo: String) {
val email = HtmlEmail()
email.hostName = "smtp.sendgrid.net"
email.setSmtpPort(587)
email.setAuthenticator(
DefaultAuthenticator(
"apikey",
"API_KEY"
)
)
email.isSSLOnConnect = true
email.setFrom(Constants.EMAIL_FROM)
email.subject = "Forgot Password"
email.setHtmlMsg("<html><body><div style='background:red;'>Hello</div></body></html>")
email.addTo(emailTo)
email.send()
}
What I want to do is
email.sendTemplate(MustacheContent("forgotPassword.hbs", mapOf("token" to token)))
how I can send this?
resources/templates/reset.hbs
<html>
<body>
<h1>Hello</h1>
<p>Please visit the link below to reset your password</p>
Reset your password
</body>
</html>
You can compile and render a template via a Mustache factory to get an HTML string. Here is an example:
val factory = DefaultMustacheFactory("templates")
embeddedServer(Netty, port = 3333) {
install(Mustache) {
mustacheFactory = factory
}
routing {
post("/") {
val content = MustacheContent("forgotPassword.hbs", mapOf("token" to "my-token"))
val writer = StringWriter()
factory.compile(content.template).execute(writer, content.model)
val html = writer.toString()
// Send email with an HTML
}
}
}.start(wait = true)
I am trying to set up an emailing system for users on my website. I am using nextJS and have an api endpoint to send emails. To send the emails I am using emailJS and sending the email to myself with a custom body. Here is the code for my email.js file:
import { SMTPClient } from 'emailjs';
export default function handler(req, res) {
const {body, subject}=req.body;
// console.log(process.env)
const client = new SMTPClient({
user: "test#gmail.com",
password: "passward",
host: 'smtp.gmail.com',
ssl:true
});
try{
client.send(
{
text: `${body}`,
from: "test#gmail.com",
to: "test#gmail.com",
subject: `${subject}`,
}
)
}
catch (e) {
res.status(400).end(JSON.stringify({ message: e.message }))
return;
}
res.status(200).end(JSON.stringify({ message:'Mail sending' }))
}
The code works when I use it on localhost but it does not work when I deploy to amplify. When I try to make a post request on amplify I get status 200 with the {"message":"Mail sending"}. However, the gmail account never gets the email. I do not get an error message. I do not have 2 step verification on and have allowed less secure apps, but still no emails are being sent. I would really appreciate any help.
The emailjs library utilizes a queuing system for sending emails. This means that the send method adds the email to the queue and sends it at a later time. This can cause issues when using the send method within a lambda function, as the function may close before the email has been sent. To ensure that the email is sent before the lambda function closes, you can use the sendAsync method instead. This method returns a promise that will be resolved when the email has been successfully sent.
To send an email using the sendAsync method, you can do the following:
await client.sendAsync(
{
text: `${body}`,
from: "test#gmail.com",
to: "test#gmail.com",
subject: `${subject}`,
}
)
im New in .Net 5 and Blazor , im trying to make registration form with Identity , after i add the pages with scaffolding i want to add email confirmation i tried some example but not passed yet
https://dotnetcoretutorials.com/2017/11/02/using-mailkit-send-receive-email-asp-net-core/
please any idea or example to do this?
"EmailConfiguration": {
"SmtpServer": "smtp.gmail.com",
"SmtpPort": 465,
"SmtpUsername": "email#gmail.com",
"SmtpPassword": "password"}
I Solved my trouble with MailKit
https://jasonwatmore.com/post/2020/07/15/aspnet-core-3-send-emails-via-smtp-with-mailkit
important notes
to use Gmail as a sender enable Less secure app from email account setting
// create email message
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse("from_address#example.com"));
email.To.Add(MailboxAddress.Parse("to_address#example.com"));
email.Subject = "Test Email Subject";
email.Body = new TextPart(TextFormat.Plain) { Text = "Example Plain Text Message Body" };
// send email
using var smtp = new SmtpClient();
smtp.Connect("smtp.ethereal.email", 587, SecureSocketOptions.StartTls);
smtp.Authenticate("[USERNAME]", "[PASSWORD]");
smtp.Send(email);
smtp.Disconnect(true);
I have a validated domain, and sending a direct email via the AWS Pinpoint console works fine. However, I can't get the same to work with Boto3 send_messages.
I get {'DeliveryStatus': 'PERMANENT_FAILURE', 'StatusCode': 400, 'StatusMessage': 'Request must include message email message.'}
But I have a MessageConfiguration Default Message with a simple string for Body, and I've tried BodyOverride as well. No problems sending SMS.
I've been unable to snag an example of send_messages, and I think if I saw a working example of an email send, that'd be all I need.
Snippet:
response = ppClient.send_messages(
ApplicationId=pinpointId,
MessageRequest={
'Addresses': {
'mguard#{validateddomain}.com': {
# 'BodyOverride': 'Hello from Pinpoint!',
'ChannelType': 'EMAIL',
}
},
'MessageConfiguration': {
'DefaultMessage': {
'Body': 'Default Message for EMAIL.',
'Substitutions': {}
}
}
}
)
I have written the code for sending email in email.js as follows:
Accounts.emailTemplates.siteName = "xyz";
Accounts.emailTemplates.from = "xyz <admin#xyz.com>";
Accounts.emailTemplates.verifyEmail = {
subject() {
return "[xyz] Verify Your Email Address";
}
};
Accounts.emailTemplates.verifyEmail.text = function( user, url) {
let emailAddress = user.emails[0].address,
urlWithoutHash = url.replace( '', '' ),
supportEmail = "support#xyz.com",
emailBody = `To verify your email address (${emailAddress}) visit the following link:\n\n${urlWithoutHash}\n\n If you did not request this verification, please ignore this email. If you feel something is wrong, please contact our support team: ${supportEmail}.`;
return emailBody;
}
The email is working and all I want is to change the Design. How to design the email body? Can I insert the html code inside the email body so that I can have a proper responsive email design? I have tried in many ways. Can anyone please help me out?
I have used mail gun API for sending emails is there anyway to use template.
I have tried with grunt email template and am struck with that I need help to get complete my task.
You can create an email template using SSR package.
Accounts.emailTemplates.verifyEmail.html = function (user, url) {
SSR.compileTemplate( 'registartionEmail', Assets.getText( 'email_templates/registration_confirm.html' ) );
var emailData = {
x: y;
};
return SSR.render( 'registartionEmail', emailData );
};
To handle the process of converting templates into raw HTML on the server, you need to add a package to your application called meteorhacks:ssr. Once you have the package installed, you can store plain HTML files inside your /private directory and then convert them later, passing any data to replace handlebars helpers like {{name}} in the process.
For example, here is some code I have used to send a welcome email when new users register:
import { SSR } from 'meteor/meteorhacks:ssr';
const getHTMLForEmail = (templateName, data) => {
SSR.compileTemplate(templateName, Assets.getText(`email/templates/${templateName}.html`));
return SSR.render(templateName, data);
};
const sendEmail = (emailAddress, html) => {
if (emailAddress.includes('#')) {
const emailData = {
to: emailAddress,
from: 'Test Email <hello#test.io>',
subject: 'Welcome aboard, team matey!',
html,
};
Meteor.defer(() => Email.send(emailData));
}
};
export const sendWelcomeEmail = (user, profile) => {
let email;
if (user.services.facebook) {
email = user.services.facebook.email;
} else if (user.services.google) {
email = user.services.google.email;
}
const data = {
email,
name: profile && profile.name ? profile.name : '',
url: 'www.google.com',
};
const html = getHTMLForEmail( 'welcome-email', data );
sendEmail(data.email, html);
};
You will find the following two articles from Meteor Chef very useful (also shows how the html email template looks like):
Using the email package
Sign up with email verification