I know in C# you can create an SMTPClient, so long as you have the valid settings for the host; something along these lines:
System.Net.Mail.SmtpClient SMTPClient = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["SMTPHost"]);
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(recipient);
message.Subject = subject;
message.From = new System.Net.Mail.MailAddress("test#test.com", "Test Address");
message.Sender = new System.Net.Mail.MailAddress("test#test.com", "Test Address");
message.Body = messageText;
SMTPClient.Send(message);
My question is: Is there a way of doing this through Google Sheets scripting?
I've found the GMailApp class in their documentation, but that obviously only works if you have an associated GMail account.
Related
I'm using a web application through which I'm sending an email.
The SMTP host is GMAIL.
I'm using Java 1.8 and JavaMail 1.6.2.
Is there any alternative to the code written below? (credits: https://hellokoding.com/sending-email-through-gmail-smtp-server-with-java-mail-api-and-oauth-2-authorization/)
void sendMail(String smtpServerHost, String smtpServerPort, String smtpUserName, String smtpUserAccessToken, String fromUserEmail, String fromUserFullName, String toEmail, String subject, String body) {
try {
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", smtpServerPort);
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(fromUserEmail, fromUserFullName));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
msg.setSubject(subject);
msg.setContent(body, "text/html");
SMTPTransport transport = new SMTPTransport(session, null);
transport.connect(smtpServerHost, smtpUserName, null);
transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", smtpUserName, smtpUserAccessToken).getBytes())), 235);
transport.sendMessage(msg, msg.getAllRecipients());
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
}
Specifically I'm very confused about these two issues:
is the following line truly the only way to set the access token in the Transport?
transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", smtpUserName, smtpUserAccessToken).getBytes())), 235);
I've been searching throughout the web but I don't seem to find an answer, basically because every other way I've attempted has resulted in NO success.
Is it true that Google has not (yet) implemented a CLIENT credentials grant type?
How else could I send emails through my web application without the user interaction (which I don't have)?
Thank you
Try this:
//TLS and OAuth2
String address = "my.smtpserver.com";
Integer port = 587;
String user = "my_username";
String accesstoken = "my_accesstoken";
String sender = "me#mycompany.com";
String recipients = "you#yourcompany.com;someone#theircompany.com";
String subject = "Test";
String body = "This is a test.";
Properties properties = new Properties();
properties.put("mail.smtp.host", address);
properties.put("mail.smtp.port", port.toString());
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth.mechanisms", "XOAUTH2");
properties.put("mail.debug.auth", "true");
Session session = Session.getInstance(properties);
session.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(sender));
String s = recipients.replace(';', ',');
mimeMessage.addRecipients(MimeMessage.RecipientType.TO,
InternetAddress.parse(s));
mimeMessage.setSubject(subject);
MimeMultipart mimeMultipart = new MimeMultipart();
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setText(body);
mimeMultipart.addBodyPart(mimeBodyPart);
mimeMessage.setContent(mimeMultipart);
Transport transport = session.getTransport();
transport.connect(user, accesstoken);
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
transport.close();
session = null;
I am doing an MVC application and trying to send an email to registered user for his account activation and email account verification.
Its working Fine on LocalHost but when i Deployed it on live server it gave me this error:
Error.String reference not set to an instance of a String. Parameter name: s
Following is the Code which i have written for sending email:
var verifyUrl = string.Empty;
verifyUrl = Request.Url.GetLeftPart(UriPartial.Authority) + "/Account/AccountVerify?I=" + NewUserID;
string body = "<html><head><meta content=\"text/html; charset=utf-8\" /></head><body><p>Dear " + objuserdet.Email + "" +
", </p><p>To verify your account, please click the following link:</p>"
+ "<p><a href=\"" + verifyUrl + "\" target=\"_blank\">" + verifyUrl + ""
+ "</a></p><div>Best regards,</div><div>" + NewUserID + " Team.</div><p>Note: Do not forward "
+ "this email. The verify link is private.</p></body></html>";
string To = objuserdet.Email;
string Subject = "Account Activation";
SendEmail(To,Subject,body);
and here is the Email Method:
public void SendEmail(string To, string Subject, string Body)
{
try
{
MailMessage mail = new MailMessage();
// mail.From = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["EmailID"].ToString());
mail.From = new MailAddress("blue.naina9#gmail.com");
mail.To.Add(To.Trim());
mail.Subject = Subject.Trim();
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
System.Net.NetworkCredential BasicAuthenticationInfo = new System.Net.NetworkCredential("blue.naina9#gmail.com","*******");
smtp.Timeout = 600000;
smtp.UseDefaultCredentials = false;
smtp.Credentials = BasicAuthenticationInfo;
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
}
..
Any Help will be appreciated.
Thanks
Posting stack trace would have helped. How ever the only place I think this kind of error will come is
mail.To.Add(To.Trim());
replace string To = objuserdet.Email;
with
if(!string.IsNullOrEmpty(objuserdet.Email)){
string To = objuserdet.Email;
}
else{
throw new Exception("Email is null!");
}
Check if this works!
This Error Occurs because Gmail blocks Sign-in Request of Sender Email Account From my Application due to change in my current location and Deployment server location(that is in US).
So i added a US based Account for Sending Email and it stats working Fine For me..
Hope this Help Others As well..
I am managing to send mails just fine with send grid, attachment too no issues. But I am having problems embedding images into the body of the HTML mail
Here is the code that I am using, put together after reading various examples on this issue. Anyone know where I am going wrong, regards...
MemoryStream msLogo = new MemoryStream(obj.logo);
Bitmap b = new Bitmap(msLogo);
ImageConverter ic = new ImageConverter();
Byte[] ba = (Byte[])ic.ConvertTo(b, typeof(Byte[]));
MemoryStream logo = new MemoryStream(ba);
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(sBody, null, "text/html");
LinkedResource imageResource = new LinkedResource(logo);
var imagelink = new LinkedResource(logo, "image/png");
imagelink.ContentId = string.Format("logo", myMessage);
imagelink.TransferEncoding = TransferEncoding.Base64;
b.Save(logo, ImageFormat.Jpeg);
logo.Position = 0;
In my web application I have a ability to send email message, which works great when I debug it on my local machine, but since I deploy it to the server with IIS 8.5 it doesn't send email. Is there any special setting I need to do to enable smtp?
try
{
MailMessage mail = new MailMessage();
mail.To.Add(emails);
mail.From = new MailAddress("test#test.co.uk");
mail.Subject = title;
LinkedResource report = new LinkedResource(new MemoryStream(img), "image/png");
var contentId = Guid.NewGuid().ToString();
report.ContentId = contentId;
var body = "<p style='font-family:Arial, Helvetica, sans-serif, Century Gothic; font-size: 16px;'>" + content + "</p>";
body = body + string.Format("<img src=\"cid:{0}\" />", contentId);
var av1 = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
av1.LinkedResources.Add(report);
mail.AlternateViews.Add(av1);
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mysmtphost.com";
smtp.UseDefaultCredentials = true;
smtp.Port = 25;
//smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
smtp.EnableSsl = false;
smtp.Send(mail);
return true;
}
catch (Exception ex)
{
Debug.Write("Execption in sendEmail:" + ex.Message);
return false;
}
I have also set up SMTP service on the server and successfully send email using PowerShell, but again I cannot send email from the app even if I change to use PickupDirectoryFromIIS (the commented one).
We have an Azure hosted website that is trying to send mail over SMTP.
All I get is timeouts, here are my POP and IMAP settings followed by code. In Azure portal under the website - do i need to configure anything in Azure website settings?
My c# code below...The code uses the following values it fetches from the database :
public bool Send(string sRecipient, string sSubject, string sBody)
{
CompanyProvider obj = _db.GetCompanyProvider();
if (!obj.EmailNotifications)
return true;
MailMessage mail = new MailMessage();
mail.To.Add(sRecipient);
mail.From = new MailAddress(obj.SenderEmail);
mail.Subject = sSubject;
string Body = sBody;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = obj.SMTPHost;
smtp.Port = obj.SMTPPort;
smtp.Timeout = 8;
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential(obj.SenderEmail, obj.SenderEmailPassword);// Enter senders User name and password
//smtp.Credentials = new System.Net.NetworkCredential
//(obj.SenderEmail.Substring(0, obj.SenderEmail.IndexOf('#')), obj.SenderEmailPassword);// Enter senders User name and password
try
{
smtp.Send(mail);
return true;
}
catch (Exception ex)
{
_db.writeToErrorLog(ex.ToString(), "Unable to send mail at this time");
return false;
}
}
}
When using Azure websites.....
http://azure.microsoft.com/en-in/documentation/articles/sendgrid-dotnet-how-to-send-email/