SendGrid only sends emails to Gmail - smtp

I'm trying to integrate SendGrid API via phpMailer (also tried with php API library too). In localhost and live server I got 250 OK with phpmailer and 202 OK with API library response.
After submission (4 receiver), I've only receive 1 email to gmail. Another domain email addresses shows Delivered in SendGrid activitiy page but I dont receive these emails except Gmail.
My sender email adress and domain address already verified. Whats wrong on my code?
phpMailer
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP();
$mail->Host = 'smtp.sendgrid.net';
$mail->Port = 587;
$mail->Username = 'apikey';
$mail->Password = 'API_KEY';
$mail->SMTPAuth = true;
$mail->SMTPDebug = true;
$mail->Debugoutput = 'html';
$mail->SMTPKeepAlive = true;
$mail->SMTPSecure = 'TLS';
$mail->Priority = 3;
$mail->Encoding = 'base64';
$mail->CharSet = "utf-8";
$mail->SetFrom('sender#mail.com', $name = 'Sender Title');
$mail->AddAddress('receiver#mail.com', 'Receiver Title');
$mail->Subject = 'SendGrid Test';
$mail->MsgHTML('Mail body');
$sending = $mail->Send();
$mail->SmtpClose();
With API Library
$email = new \SendGrid\Mail\Mail();
$email->setFrom("sender#mail.com", "Example User");
$email->setSubject("Sending with Twilio SendGrid is Fun");
$email->addTo("receiver#mail.com", "Example User");
$email->addContent("text/plain", "and easy to do anywhere, even with PHP");
$email->addContent(
"text/html", "<strong>and easy to do anywhere, even with PHP</strong>"
);
$sendgrid = new \SendGrid('API_KEY');
try {
$response = $sendgrid->send($email);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
}

If your emails are sending successfully and being received by Gmail, then there is nothing wrong with your code (save for the minor issues that Synchro pointed out in the comments).
Email deliverability isn't an exact science, so there could be something in the contents of your email that triggers mail blocking for some inboxes. I'd follow the guidelines in this article on email deliverability to ensure you are setting yourself up to get emails into inboxes.
Beyond that, I would also set up the SendGrid Event Webhook. That will delivery you events based on what your emails are doing, including delivery events when an email is dropped, deferred, bounced, blocked or delivered. That may help you understand what is happening to your email.

Related

noReply mail with apps script should ignore already replied mailadresses

whats up :D
I hav set up a very, very eased up noreply mailresponder.
UseCase:
We send some kind of notification via Email from our service (Like: "Hey, check out new message")
But the receiver of that mailnotification should not respond to our email notification.
If he still does we have set up an email auto responder ->
curently what i have done with apps scripts on google is following:
function AutoResponder() {
var query = "is:unread" ;
var unread = GmailApp.search(query);
for (var i in unread)
{
var thread = unread[i];
var messages = thread.getMessages();
if (messages.length === 1) { // the reply
body =
"<p> Blabla dont reply to our email thx </p>"
options =
{
name: "This is the subject of mail",
htmlBody: body
};
thread.reply("", options);
}
}
}
Ive set a trigger like every 15 mins the code will get excecuted.
Works quite well but i have an issue:
When recipient has set an autoresponder aswell, they keep looping (sending each other this autoresponder mail) until i delete the last email of that user, so script wont be able to see that thread in the google message list screen.
But i would like to implement that in the code, somehow try to cache the sendermail and not send an response for few hours.
Is that somehow possible?
Thank you guys in advance and have a nice week guys!!

How to stop MailApp.sendEmail from sending myself a copy of the email

We are using Google Scripts to send emails after Google Forms are submitted. In the last day or two, we started receiving email delivery failures every time a form was submitted and the script ran. It is only unable to deliver messages to one account(sender#mydomain.com), which happens to be the account that the script is running as. However, this account should not be receiving a copy of this form anyways. All of the email addresses that are in the "To" field are getting the email with no issue, we are just trying to find out why we are getting this error message.
We are using the MailApp.sendEmail function and have been for years without any problem. We can't use the GmailApp functions because this account is not able to use Gmail and we've never needed to be able to in order to send emails.
In the script, when I add sender#mydomain.com to the To list, I receive the email and do not get any error messages. When I remove it from the To list, the rest of the recipients continue to receive the email but I get that error message again for sender#mydomain.com.
function formSubmitReply(e) {
var replyToAddr = "no_reply#mydomain.com";
var emailAddress = e.values[2]; // + ", sender#mydomain.com";
//Removed section that creates PDF, stores as the variable pdf
var subject = "Form Request from " + e.values[1];
var messageHtml = "<font size = 3><font face = arial>Form Request from: " + e.values[1];
var messagePlain = messageHtml.replace(/\<br\/\>/gi, '\n').replace(/(<([^>]+)>)/ig, "");
MailApp.sendEmail(emailAddress, subject, messagePlain, {htmlBody: messageHtml, name: "Sender", attachments: pdf, replyTo: replyToAddr});
}
It sounds weird to me that MailApp was working on an account that doesn't have Gmail enabled as MailApp affects the email sent Gmail quota but then I found No reports a 550 recipient rejected from MailApp. The only answer at this time looks to be wrong as MailApp sent emails are saved as sent emails on Gmail mailbox of the effective user that ran the script.

Unable to use sub account with Google Service Account

I needed to create a script that uploads the resulting screen shots to google drive.
I was hoping I could just auth in as my google user, but that seems... harder? So I abandoned that tact. Next I moved onto service accounts. This works fine (now) for my service account, but when I attempt to specify a user ($auth->sub) I get "Unauthorized client or scope in request.".
function buildService($userEmail) {
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'notsupplied#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'pathtofile.p12';
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_Auth_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
array($DRIVE_SCOPE),
$key);
$auth->sub = 'myuser#gmail.com';
$client = new Google_Client();
$client->setAssertionCredentials($auth);
return new Google_Service_Drive($client);
}
I'd love to abandon the service account and just auth with my regular google user if thats just as easy. Or solve how (in the api settings maybe?) I can ensure myuser#gmail.com can be used.
Refresh_token is the key here. In a webbrowser use this link to approve your google user:
https://accounts.google.com/AccountChooser?service=lso&continue=https%3A%2F%2Faccounts.google.com%2Fo%2Foauth2%2Fauth%3Fresponse_type%3Dcode%26scope%3Dhttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive%26redirect_uri%3Dhttps%3A%2F%2Fwww.example.com%2Foauth2callback%26access_type%3Doffline%26client_id%3D<CLIENT_ID>%26hl%3Den%26from_login%3D1%26as%3D34eac985232ba748&btmpl=authsub&hl=en&approval_prompt=force&access_type=offline
which will return a URL like https://www.example.com/oauth2callback?code=
Then post code=&client_id=&client_secret=&redirect_uri=&grant_type=authorization_code to https://accounts.google.com/o/oauth2/token
This will return a "refresh_token" parameter. Save this. Very important. If you don't get one you have to go to https://security.google.com/settings/security/permissions to revoke permissions from your app.
After you get the refresh token you're good to go:
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$client->setAccessType('offline');
$token = $client->refreshToken('<YOUR_REFRESH_TOKEN>');
$service = new Google_Service_Drive($client);

PHP mailer, gmail smtp not sending email from live server

I have the following code to send email:
$mail->IsSMTP();
$mail->Host = 'imap.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'my gmail id';
$mail->Password = 'mypassword';
$mail->SetFrom('info#somedomain.com', 'Bilafon');
$mail->Subject = $subject;
$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
$mail->MsgHTML($body);
$mail->AddAddress($email_id, $user_name);
return $mail->Send();
Its sending email from the localhost but not from the live server. On live server it shows this error:
SMTP Error: Could not authenticate
Any kind of help is appreciated
Check your gmail settings. It might be SMTP disabled from there.

How do I send an HTML Form in an Email .. not just MAILTO

I have an HTML form for people to fill out, and I want it so when they click the submit button, it will just send the email, not bring up their email and ask them to send the message themselves.
When I use:
<form action="MAILTO:emailaddress#email.com"... >
All that does is open up a new window and populates the body of the email, but I want it to just send an email.
And is there a way to format the output of what the email will look like? Instead of just a list of the field names and the entered value.
Thanks.
> 2021 Answer = Easy Way using GMail (5 Mins)
We had a similar challenge to solve yesterday, and we solved it using a Google Apps Script!
Send Email From an HTML Form Without a Backend (Server) via Google!
The solution takes 5 mins to implement and I've documented with step-by-step instructions: https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
Brief Overview
A. Using the sample script, deploy a Google App Script
Deploy the sample script as a Google Spreadsheet APP Script:
google-script-just-email.js
remember to set the TO_ADDRESS in the script to where ever you want the emails to be sent.
and copy the APP URL so you can use it in the next step when you publish the script.
B. Create your HTML Form and Set the action to the App URL
Using the sample html file:
index.html
create a basic form.
remember to paste your APP URL into the form action in the HTML form.
C. Test the HTML Form in your Browser
Open the HTML Form in your Browser, Input some data & submit it!
Submit the form. You should see a confirmation that it was sent:
Open the inbox for the email address you set (above)
Done.
Everything about this is customisable, you can easily
style/theme the form with your favourite CSS Library
and Store the submitted data in a Google Spreadsheet
for quick analysis.
The complete instructions are available on GitHub:
https://github.com/nelsonic/html-form-send-email-via-google-script-without-server
You are making sense, but you seem to misunderstand the concept of sending emails.
HTML is parsed on the client side, while the e-mail needs to be sent from the server. You cannot do it in pure HTML. I would suggest writing a PHP script that will deal with the email sending for you.
Basically, instead of the MAILTO, your form's action will need to point to that PHP script. In the script, retrieve the values passed by the form (in PHP, they are available through the $_POST superglobal) and use the email sending function (mail()).
Of course, this can be done in other server-side languages as well. I'm giving a PHP solution because PHP is the language I work with.
A simple example code:
form.html:
<form method="post" action="email.php">
<input type="text" name="subject" /><br />
<textarea name="message"></textarea>
</form>
email.php:
<?php
mail('youremail#example.com', $_POST['subject'], $_POST['message']);
?>
<p>Your email has been sent.</p>
Of course, the script should contain some safety measures, such as checking whether the $_POST valies are at all available, as well as additional email headers (sender's email, for instance), perhaps a way to deal with character encoding - but that's too complex for a quick example ;).
I actually use ASP C# to send my emails now, with something that looks like :
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form.Count > 0)
{
string formEmail = "";
string fromEmail = "from#email.com";
string defaultEmail = "default#email.com";
string sendTo1 = "";
int x = 0;
for (int i = 0; i < Request.Form.Keys.Count; i++)
{
formEmail += "<strong>" + Request.Form.Keys[i] + "</strong>";
formEmail += ": " + Request.Form[i] + "<br/>";
if (Request.Form.Keys[i] == "Email")
{
if (Request.Form[i].ToString() != string.Empty)
{
fromEmail = Request.Form[i].ToString();
}
formEmail += "<br/>";
}
}
System.Net.Mail.MailMessage myMsg = new System.Net.Mail.MailMessage();
SmtpClient smtpClient = new SmtpClient();
try
{
myMsg.To.Add(new System.Net.Mail.MailAddress(defaultEmail));
myMsg.IsBodyHtml = true;
myMsg.Body = formEmail;
myMsg.From = new System.Net.Mail.MailAddress(fromEmail);
myMsg.Subject = "Sent using Gmail Smtp";
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("testing#gmail.com", "pward");
smtpClient.Send(defaultEmail, sendTo1, "Sent using gmail smpt", formEmail);
}
catch (Exception ee)
{
debug.Text += ee.Message;
}
}
}
This is an example using gmail as the smtp mail sender. Some of what is in here isn't needed, but it is how I use it, as I am sure there are more effective ways in the same fashion.