Send Email without attachments - c#

I have a Problem i know how to send email with attachment but i want to learn that if i dont have screenshot.png then i want to send it without attachment my code is below
string email = "hammadptc93#gmail.com";
string pass = "mypassword";
NetworkCredential loginInfo = new NetworkCredential(email, pass);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress("hammadptc93#gmail.com"));
msg.Body = value;
msg.Subject = Environment.UserName +" " +
Environment.UserDomainName +" "+ Environment.SystemDirectory ;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.SendAsync(msg, "hammad");

Simply checking whether file is present or not will be enough.
if(File.Exists("screenshot.png"))
{
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
}

Use File.Exists method to check whether you have the attachment. If File.Exists returns false, side step from following lines (wrap them in a if statement)
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
Hope this helps

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

cannot send email using office 365 credentials using C#

I am trying to send email with my office 365 credentials using C#. But It is failing to send and getting exception.
How to fix this? Is it possible to send from office 365?
foreach (var filename in files)
{
String userName = "sri#MyOffice365domain.com";
String password = "password";
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.office365.com");
mail.From = new MailAddress("sri#MyOffice365domain.com");
mail.To.Add("senderaddress#senderdomain.com");
mail.Subject = "Fwd: for " + filename;
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(filename);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(userName, password);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Transaction failed. The server response was: 5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied; Failed to process message due to a permanent exception with message Cannot submit message.
How many emails are you going to send simultaneously?
foreach (var filename in files)
All Outlook APIs accessed via https://outlook.office.com/api or https://outlook.office365.com/api have a limit is 60 requests per minute, per user (or group), per app ID. So, for now, developers only can make limited APIs calls from the app. Read through the Microsoft Blog Post for more details on REST API call limitations.
Try to use the following code instead:
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("someone#somedomain.com", "SomeOne"));
msg.From = new MailAddress("you#yourdomain.com", "You");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message using Exchange OnLine";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("your user name", "your password");
client.Port = 587; // You can use Port 25 if 587 is blocked (mine is!)
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
lblText.Text = "Message Sent Succesfully";
}
catch (Exception ex)
{
lblText.Text = ex.ToString();
}

Cannot send email with ASP.NET

My Project need to send an e-mail but I cannot send it. I don't know why. Last month I can send but today I cannot.
string url = Request.Url.AbsoluteUri;
string hyperlink = "<a href='" + url + "'>" + url + "</a>";
NetworkCredential loginInfo = new NetworkCredential("***examplemail***", "myPassword");
MailMessage msg = new MailMessage();
msg.From = new MailAddress("***examplemail***");
msg.To.Add(new MailAddress("***ToEmail***"));
msg.Bcc.Add(new MailAddress("***examplemail***"));
msg.Subject = "TEST";
msg.Body = "Hi, TEST Send E-mail";
msg.IsBodyHtml = false;
SmtpClient client = new SmtpClient("smtp.gmail.com", 995); // tried 25 587 and 995
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
** It didn't have any error but I didn't send too.
I wouldn't use the port number in here.
SmtpClient client = new SmtpClient("smtp.gmail.com", 995); // tried 25 587 and 995
This way it sends. I tried and it worked. I am saying that it should look like
SmtpClient client = new SmtpClient("smtp.gmail.com");
If you check SmtpClient's constructor while writing the code you will see that it has one overload.
Try this:
using System.Net;
using System.Net.Mail;
namespace consSendMail
{
class Program
{
static void Main(string[] args)
{
SmtpClient smtpClient = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
Credentials = new NetworkCredential("yourmail", "yourpassword")
};
var mailMessage = new MailMessage();
mailMessage.Subject = "Subject";
mailMessage.From = new MailAddress("yourmail", "yourname");
mailMessage.IsBodyHtml = true;
mailMessage.Body = "your message";
mailMessage.To.Add( new MailAddress("destinationemail") );
smtpClient.Send(mailMessage);
mailMessage.Dispose();
smtpClient.Dispose();
}
}
}

Sending email problem by Gmail account

I'm trying to send a email in C# using Gmail. I want the 'from' header to have another my own specified email address whenever user receive email. Could anyone please tell me how can I do this?
MailMessage mailMsg = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(username, password);
MailAddress mailAdd = new MailAddress("jack2#gmail.com");
mailMsg.Sender = new MailAddress(username);
mailMsg.From = mailAdd;
//mailMsg.Headers.Add("Sender",username);
mailMsg.Bcc.Add(builder.ToString());
mailMsg.Subject = txtSubject.Text;
mailMsg.Body = txtBody.Text;
mailMsg.IsBodyHtml = chkHtmlBody.Checked;
if (System.IO.File.Exists(txtAttechments.Text))
{
System.Net.Mail.Attachment attechment = new Attachment(txtAttechments.Text);
mailMsg.Attachments.Add(attechment);
}
client.Send(mailMsg);
In above code 'username' and 'password' fields contain another email address and password. The received email having 'from' header with value
TRY this if your mail provide is not gmail and also not using IMAP services.
MailMessage mailMsg = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "mail.youdomain.com"; //////EDITED
client.EnableSsl = false; //////EDITED
client.Credentials = new System.Net.NetworkCredential(username, password);
MailAddress mailAdd = new MailAddress("jack2#gmail.com");
mailMsg.Sender = new MailAddress(username);
mailMsg.From = mailAdd;
//mailMsg.Headers.Add("Sender",username);
mailMsg.Bcc.Add(builder.ToString());
mailMsg.Subject = txtSubject.Text;
mailMsg.Body = txtBody.Text;
mailMsg.IsBodyHtml = chkHtmlBody.Checked;
if (System.IO.File.Exists(txtAttechments.Text))
{
System.Net.Mail.Attachment attechment = new Attachment(txtAttechments.Text);
mailMsg.Attachments.Add(attechment);
}
client.Send(mailMsg);

Authentication Error in C# Send Mail App

I'm developing a simple send mail app in C#, using my CMail Server:
MailMessage mail = new MailMessage("from#mail.com", "destination#mail.com");
mail.Subject = "Sub";
mail.Body = "Hi!";
SmtpClient smtp = new SmtpClient("MyServer");
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("user", "pass");
smtp.UseDefaultCredentials = false;
smtp.Credentials = cred;
smtp.Send(mail);
Obviously i ommited my account information, so, this code throws me an Authentication Exception for some reason. I first thought that the code was wrong, so i change the info to my gmail account and everything goes fine, with the only SMTP server that i having trouble is with the CMail. Is there a problem with .NET and CMail's SMTP ?
Thanks for the help and comments!
Try adding:
smtp.EnableSsl = true;
If you are using 2-step verification then you will need to add application specific password.
Full work sample
public static void sendEmail()
{
//for use GMAIL require enable -
//https://myaccount.google.com/lesssecureapps?rfn=27&rfnc=1&eid=39511352899709300&et=0&asae=2&pli=1
Console.WriteLine("START MAIL SENDER");
//Авторизация на SMTP сервере
SmtpClient Smtp = new SmtpClient("smtp.gmail.com", 587);
Smtp.EnableSsl = true;
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
Smtp.UseDefaultCredentials = false;
//username password
Smtp.Credentials = new NetworkCredential("rere", "rere");
//Формирование письма
MailMessage Message = new MailMessage();
Message.From = new MailAddress("rere#gmail.com");
Message.To.Add(new MailAddress("rere#gmail.com"));
Message.Subject = "test mesage";
Message.Body = "tttt body";
string file = "D:\\0.txt";
if (file != "")
{
Attachment attach = new Attachment(file, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attach.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
Message.Attachments.Add(attach);
Console.WriteLine("ADD FILE [" + file + "]");
}
try
{
Smtp.Send(Message);
MessageBox.Show("SUCCESS");
}
catch { MessageBox.Show("WRONG"); }
}

Categories