Converting SMTP Sendgrid to Sendgrid API - c#

Currently replacing the old SMTP Sendgrid to API Sendgrid and I noticed that there are some differences in their code.But I was thinking that since they are both sendgrid it will just work. What I did is to add this SendGridClient.SendEmailAsync(Message); in the end. But it says
cannot convert from system.net.mail.mailmessage to sendgrid.helpers.mail.sendgridmessage
Is this the correct way of converting it?
Below is the code.
try
{
string SendGridKey = ConfigurationManager.AppSettings["SendGridKey"];
var SendGridClient = new SendGridClient(SendGridKey);
using (MailMessage MessageContent = new MailMessage())
{
MessageContent.From = new MailAddress(From);
MessageContent.To.Add(new MailAddress(To));
MessageContent.Subject = Subject;
MessageContent.Body = (TextBody);
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView Alternate = AlternateView.CreateAlternateViewFromString(HtmlBody, mimeType);
Message.AlternateViews.Add(Alternate);
if (AttachedFileName == true)
{
Attachment AttachedFile = new Attachment(HttpRuntime.AppDomainAppPath + "Path\\" + AttachedFileName);
MessageContent.Attachments.Add(AttachedFile);
}
//using (SmtpClient Client = new SmtpClient())
//{
// Client.EnableSsl = true;
// Client.Send(MessageContent);
//}
SendGridClient.SendEmailAsync(Message);
}
return;
}

For sending mail using SendGrid API, you need to create com.sendgrid.Request object. Adding code for java:
import com.sendgrid.Content;
import com.sendgrid.Email;
import com.sendgrid.Mail;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.SendGrid;
Email from = new Email("<FROM_EMAIL>");
String subject = "<SUBJECCT>";
Email to = new Email("<TO_EMAIL>");
Content content = new Content("text/plain", message);
Mail mail = new Mail(from, subject, to, content);
SendGrid sg = new SendGrid(SendGridKey);
Request request = new Request();
try {
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
sg.api(request);
log.info("Main sent successfully");
} catch (IOException ex) {
log.info("Error while sending mail: {}", ex.toString());
}

Related

Adding attachments using url in mail with C sharp

I can send attachments with URLs, But, looking for support to send a file with an attachment. that too should download from url and attach with mail.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#email.com");
//to mail address
mail.To.Add(txtEmail.Text);
//Add the Attachment
mail.Attachments.Add(data);
//set the content
mail.Subject = txtSubject.Text;
mail.Body = "Kindly find the below attachments with the link, https://www.python.org/static/img/python-logo#2x.png";
//send the message
SmtpClient smtp = new SmtpClient("*****.********.net");
NetworkCredential Credentials = new NetworkCredential("mymail#email.com", "********");
smtp.Credentials = Credentials;
smtp.Send(mail);
Here I'm sending mail with URL as a file,
But I want to attach a file instead of sending a link
The sample URL was added as an image link.. But I wanted to add a pdf link..
In this case, I want to download a file and attach it with mail,
I use it mostly in my all projects it's working fine. its with base 64
First, make sure your Gmail account is turned on for sending emails.
public static async Task SendEmail(string toUser, string subject, string body
, string username, string password, string port, string smtpServer, string ccUsers = "", string base64Url = "")
{
var toAddress = new System.Net.Mail.MailAddress(toUser, toUser);
System.Net.Mail.MailMessage emessage = new System.Net.Mail.MailMessage();
emessage.To.Add(toAddress);
if (!string.IsNullOrEmpty(ccUsers))
{
string[] ccIds = ccUsers.Split(',');
foreach (string item in ccIds)
{
emessage.CC.Add(new System.Net.Mail.MailAddress(item));
}
}
emessage.Subject = subject;
emessage.From = new System.Net.Mail.MailAddress(username);
emessage.Body = body;
emessage.IsBodyHtml = true;
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
if (!string.IsNullOrEmpty(base64Url))
{
base64Url = base64Url.Replace("data:image/jpeg;base64,", "");
var imageBytes = Convert.FromBase64String(base64Url);
var stream = new MemoryStream(imageBytes);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg);
System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(stream, ct);
at.ContentDisposition.FileName = "Invoice.jpeg";
emessage.Attachments.Add(at);
}
var netCredential = new System.Net.NetworkCredential(username, password);
sc.Host = smtpServer;
sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
sc.UseDefaultCredentials = false;
sc.Credentials = netCredential;
sc.EnableSsl = true;
sc.Port = Convert.ToInt32(port);
await sc.SendMailAsync(emessage);
}
It works fine and mail directly reaches inbox instead of spam.. also can able to attach files from serverpath. Thank you everyone who wish to answer my questions..
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#gmail.com");
mail.To.Add("tomail#gmail.com");
//set the content
string filename = "Report1";
string fileurl = Server.MapPath("..");
fileurl = fileurl + #"\mailserver\pdf\generated\" + filename + ".pdf";
//mail.Attachments.Add(new Attachment(fileurl));
if (!string.IsNullOrEmpty(fileurl))
{
Attachment attachment = new Attachment(fileurl, MediaTypeNames.Application.Pdf);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(fileurl);
disposition.ModificationDate = File.GetLastWriteTime(fileurl);
disposition.ReadDate = File.GetLastAccessTime(fileurl);
disposition.FileName = Path.GetFileName(fileurl);
disposition.Size = new FileInfo(fileurl).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mail.Attachments.Add(attachment);
}
mail.Subject = "Subject Text";
mail.Body = "Body Text";
//send the message
SmtpClient smtp = new SmtpClient("smtpout.****.******server.net");
NetworkCredential Credentials = new NetworkCredential("mymail#gmail.com", "Password#123");
smtp.Credentials = Credentials;
//smtp.EnableSsl = true;
smtp.Send(mail);
Response.Write("<center><span style='color:green'><b>Mail has been send successfully!</b></span></center>");
}
catch (Exception ex)
{
//Response.Write("<center><span style='color:red'><b>"+ ex + "</b></span></center>");
Response.Write("<center><span style='color:red'><b>Failed to send a mail...Please check your mail id or Attachment missing</b></span></center>");
}
}

Send email using c#

I am trying to send email using C# but I am getting below error.
Mailbox was unavailable. The server response was: Relay access denied. Please authenticate.
I am not sure why I am getting this error. Here, I am using smtp2go third party to send this email.
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#wraptite.com");
mail.To.Add("test1#gmail.com");
mail.Subject = "Test Email";
mail.Body = "Report";
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
//SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
I've tried your code and it work fine.
But in my case, to use the smtp server, from(email address of sender) must use the same domain to authenticate.(but gmail is available to this Send emails from a different address or alias)
So, If your SMTP server connect to smtp2go.com, try as below.
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail#smtp2go.com");
Or if you need to use service of smtp2go, it would be better use rest API.
Here is updated by your comment when using gmail.
Gmail required secure app access. that's a reason why code is not work.
So, there is two options for this.
1. Update your gmail account security
(origin idea from here : C# - 이메일 발송방법)
Go to here and turn on "Less secure app access". after doing this your code will work.(it works)
2. Using "Google API Client Library for .NET."
I think this is not so easy, check this out, I found an answer related with this here
#region SendMail
//Mail Setting
string EmailSubject = "EmailSubject";
string EmailBody = "EmailBody";
try
{
string FromAddress = "abc#gmail.com";
string EmailList = "abc1#gmail.com";
string EmailServer = "ipofemailserver";
using (var theMessage = new MailMessage(FromAddress, EmailList))
{
// Construct the alternate body as HTML.
string body = "EmailBody";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
theMessage.AlternateViews.Add(alternate);
theMessage.Subject = EmailSubject;
theMessage.IsBodyHtml = true;
SmtpClient theSmtpServer = new SmtpClient();
theSmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
theSmtpServer.Host = EmailServer;
theSmtpServer.Send(theMessage);
}
}
catch (Exception ex)
{
string AppPath = AppDomain.CurrentDomain.BaseDirectory;
string ErrorPath = AppDomain.CurrentDomain.BaseDirectory + "File\\Error\\";
string OutFileTime = DateTime.Now.ToString("yyyyMMdd");
using (StreamWriter sw = new StreamWriter(ErrorPath + OutFileTime + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + ":");
sw.WriteLine(ex.ToString());
sw.Close();
}
}
#endregion

How to put an image file into a MemoryStream and attach it into an Email

I encrypted an image,
Now I need to read that image, decrypt and attach it into an email.
For first step I try to put an image file and attach it into an Email,
but when i receive email, the attached image is corrupted !
I try many different ways, but without success.
(I created windows application project just for test, Eventually I need to use solution in MVC Web Application project)
private void btnSend_Click(object sender, EventArgs e)
{
var filePath = "D:\\3.jpg"; // path to none encrypted image file
var ms = new MemoryStream(File.ReadAllBytes(filePath));
// Create attachment
var attach = new Attachment(ms, new ContentType(MediaTypeNames.Image.Jpeg));
attach.ContentDisposition.FileName = "sample.jpg";
// Send Email
IMailSender mailSender = new MailSender();
var isSuccess = mailSender.Send(
"sample email title",
"sample#gmail.com",
"sample subject",
"sample body",
new Attachment[] { attach });
MessageBox.Show(isSuccess ? "Email sent successfully" : mailSender.ErrorMessage);
}
using (MailMessage Message = new MailMessage())
{
Message.From = new MailAddress("from#mail.com");
Message.Subject = "My Subject";
Message.Body = "My Body";
Message.To.Add(new MailAddress("to#mail.com"));
//Attach more file
foreach (var item in Attachment)
{
MemoryStream ms = new MemoryStream(File.ReadAllBytes(filePath));
Attachment Data = new Attachment(ms, "FileName");
ContentDisposition Disposition = Data.ContentDisposition;
Disposition.CreationDate = DateTime.UtcNow.AddHours(-5);
Disposition.ModificationDate = DateTime.UtcNow.AddHours(-5);
Disposition.ReadDate = DateTime.UtcNow.AddHours(-5);
Data.ContentType = new ContentType(MediaTypeNames.Application.Pdf);
Message.Attachments.Add(Data);
}
SmtpClient smtp = new SmtpClient("SmtpAddress", "SmtpPort");
smtp.Credentials = new NetworkCredential("SmtpUser", "SmtpPassword");
await smtp.SendMailAsync(Message);
}
I hope this helps

Send raw bulkmail using aws ses ApI interface(Empty required header 'To'.)

Hi I am trying to send bulkmail with attachment using amazon ses. I can able to send mails with attachment but my to-mails are appearing for all the users that I have send. I am trying to add those destination mails in bcc fields but it is throwing an error Empty required header 'To'.
This is what I've already tried:
private static BodyBuilder GetMessageBody()
{
var body = new BodyBuilder()
{
HtmlBody = #"<p>Amazon SES Test body</p>",
TextBody = "Amazon SES Test body",
};
body.Attachments.Add(#"G:\me.jpg");
return body;
}
private static MimeMessage GetMessage()
{
var message = new MimeMessage();
List<string> to = new List<string>(50);
to.Add("xxxxxx#gmail.com");
to.Add("xxxxxx#gmail.com");
message.From.Add(new MailboxAddress(ConfigurationManager.AppSettings["senderaddress"], ConfigurationManager.AppSettings["senderaddress"]));
for (int i = 0; i < to.Count; i++)
{
message.Bcc.Add(new MailboxAddress(string.Empty,to[i]));
//message.To.Add(new MailboxAddress(string.Empty, "xxxxx#gmail.com"));
//message.To.Add(new MailboxAddress(string.Empty, "xxxxxx#gmail.com"));
}
message.Subject = "Amazon SES Test";
message.Body = GetMessageBody().ToMessageBody();
return message;
}
private static MemoryStream GetMessageStream()
{
var stream = new MemoryStream();
GetMessage().WriteTo(stream);
return stream;
}
private void SendEmails()
{
var credentals = new BasicAWSCredentials(ConfigurationManager.AppSettings["AccessKey"], ConfigurationManager.AppSettings["SecretAccessKey"]);
using (var client = new AmazonSimpleEmailServiceClient(credentals, RegionEndpoint.USEast1))
{
var sendRequest = new SendRawEmailRequest { RawMessage = new RawMessage(GetMessageStream()) };
try
{
var response = client.SendRawEmail(sendRequest);
}
catch (Exception e)
{
}
}
}
You need at least 1 email address in to 'To' field. Perhaps send the email to yourself and add the others as a BCC.
Instead of using the BCC header to send out bulk mails, IMHO you should send one email with a clear "to" header to each of the recipients. So instead looping through recipients and adding them to BCC you should rather create and send a message there.

how to convert non-mime message to mime mail message in c#

i got a mail message which is not a MIME message
can not get Content-Type
can not get attachment
how to convert this message into MIME message
foreach (AE.Net.Mail.Lazy<MailMessage> message in messages)
{
MailMessage m = message.Value;
string sender = m.From.Address;
ICollection<Attachment> cc = m.Attachments;
foreach (Attachment aa in cc)
{
System.IO.File.WriteAllBytes(#"C:\Users\LAB-User2\Desktop\EmailAttachments\" + aa.Filename, aa.GetData());
}
}
Update
does this disposition work for non-mime message?
public string GetDisposition()
{
return this["Content-Disposition"]["boundary"];
}
string disposition = Headers.GetDisposition();
if (!string.IsNullOrEmpty(disposition))
{
//else this is a multipart Mime Message
using (var subreader = new StringReader(line + Environment.NewLine + reader.ReadToEnd()))
ParseMime(subreader, disposition);
}
else
{
//SetBody((line + Environment.NewLine + reader.ReadToEnd()).Trim());
}
can i send non-mime email to myself ? so that i can receive mime format email?
when i try this, i can not email to myself
ImapClient imap = new ImapClient("imap.gmail.com", "hello#gmail.com", "pwd", ImapClient.AuthMethods.Login, 993, true, true);
//imap.Connect("imap.gmail.com", 993, true, true);
imap.SelectMailbox("INBOX");
//MailMessage[] mm = imap.GetMessages(imap.GetMessageCount() - 1, imap.GetMessageCount() - 10, false, false);
AE.Net.Mail.Lazy<AE.Net.Mail.MailMessage>[] messages = imap.SearchMessages(SearchCondition.Unseen(), false);
// Run through each message:
foreach (AE.Net.Mail.Lazy<AE.Net.Mail.MailMessage> message in messages)
{
AE.Net.Mail.MailMessage mm = message.Value;
//create the mail message
//var mail = new MailMessage();
var mail = new System.Net.Mail.MailMessage();
//set the addresses
mail.From = new MailAddress("me#mycompany.com", "demo");
mail.To.Add("hello#gmail.com");
//set the content
mail.Subject = "This is an email";
//first we create the Plain Text part
//var plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
//var htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");
ICollection<AE.Net.Mail.Attachment> cc = mm.AlternateViews;
foreach (AE.Net.Mail.Attachment aa in cc)
{
try
{
System.IO.File.WriteAllBytes(#"C:\Users\LAB-User2\Desktop\EmailAttachments\" + aa.Filename, aa.GetData());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//mail.AlternateViews.Add(b);
}
var plainView = AlternateView.CreateAlternateViewFromString(mm.Raw, null, "text/plain");
mail.AlternateViews.Add(plainView);
//send the message
var smtp = new SmtpClient("smtp.gmail.com", 587); //specify the mail server address
smtp.Credentials = new System.Net.NetworkCredential("hello#gmail.com", "pwd");
smtp.EnableSsl = true;
smtp.Send(mail);
smtp = null;
mail.Dispose();
You can use this sample:
//create the mail message
var mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me#mycompany.com");
mail.To.Add("you#yourcompany.com");
//set the content
mail.Subject = "This is an email";
//first we create the Plain Text part
var plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
var htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
//send the message
var smtp = new SmtpClient("127.0.0.1"); //specify the mail server address
smtp.Send(mail);

Categories