Blazor .Net 5 Identity Registration With email confirmation - email

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);

Related

STMP client from email js not working on aws amplify

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}`,
}
)

Sending email without actually signing in to gmail account from flutter app

I want to send user an email on order confirmation. For this I'm using mailer 3.2.1 package.
https://pub.dev/packages/mailer
At below line in below code snippet, I'm getting prompt that saying 'gmail' is deprecated and shouldn't be used. Favor gmailUserXoauth2 as username/password is considered a Less-Secure-Apps.
final smtpServer = gmail(username, password);
After replacing gmail with gmailUserXoauth2 in above line, I get The method 'gmailUserXoauth2' isn't defined
Below is the code snippet
String username = 'xxx#gmail.com';
String password = 'xxx';
final smtpServer = gmail(username, password);
// Create our message.
final message = Message()
..from = Address(username, 'Your name')
..recipients.add('destination#example.com')
..ccRecipients.addAll(
['destCc1#example.com', 'destCc2#example.com'])
..bccRecipients.add(Address('bccAddress#example.com'))
..subject =
'Test Dart Mailer library :: 😀 :: ${DateTime.now()}'
..text =
'This is the plain text.\nThis is line 2 of the text part.'
..html =
"<h1>Test</h1>\n<p>Hey! Here's some HTML content</p>";
try {
final sendReport = await send(message, smtpServer);
print('Message sent: ' + sendReport.toString());
} on MailerException catch (e) {
print('Message not sent.');
for (var p in e.problems) {
print('Problem: ${p.code}: ${p.msg}');
}
}
Upon googling this issue I have come across this solution.
https://stackoverflow.com/a/58732280/7290043
This solution gives suggest following
Enable "Access for less secure apps" to use Gmail without OAuth 2.0
Sign in with Google account using the google_sign_in package and then send email
But I don't want to do either of these. I dont want to send email after signing in to google with google_sign_in package
What do I do now?
You can follow the guide here. User login is needed for authentication for emails to be sent from the Flutter app. XOAUTH2 is used in the sample code provided in the guide, it redirects users to a login page for authentication.

SMTP email slow to send with nodemailer and amazon SES

I'm trying to send emails inside next.js api functions. I have the following code:
import nodemailer, { SentMessageInfo } from "nodemailer";
export default async ({ to, subject, text, html }: Props) => {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: "email-smtp.us-east-1.amazonaws.com",
port: 465,
secure: true,
auth: {
user: process.env.AWS_SES_USERNAME,
pass: process.env.AWS_SES_PASSWORD,
},
});
console.log("Sending email to", to);
// send mail with defined transport object
let info: SentMessageInfo = await transporter.sendMail({
from: '"Me" <help#myemail.io>', // sender address
to,
subject,
text,
html: html,
});
console.log("Message sent: %s", info.messageId);
return info.messageId;
};
Sometimes this can take minutes to send but I have no idea why. How would one go about debugging this? Is it possible that my Amazon SES SMTP server is throttling me? I'm not even sending emails that frequently.

Change the design of email body

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

send an email using a template - grails

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.