Attach text file to mail using C# for Windows-mobile - c#

I have this sample C# code for sending mail Through Windows-Mobile 6.5:
EmailMessage message = new EmailMessage();
Recipient myrecipient = new Recipient("Gmail", "MyMail#gmail.com");
message.To.Add(myrecipient);
message.Subject = "test from Windows-Mobile";
message.BodyText = "this is the test from Windows-Mobile";
message.Send("Gmail");
MessagingApplication.Synchronize("Gmail");
SetForegroundWindow(this.Handle);
How to send for more than one mail address ?
How to attach text file to mail ?

Try this:
To attach file with more details like name/size.
Attachment attachment = new Attachment(outputFile, MediaTypeNames.Text.Html);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(outputFile);
disposition.ModificationDate = File.GetLastWriteTime(outputFile);
disposition.ReadDate = File.GetLastAccessTime(outputFile);
disposition.FileName = Path.GetFileName(outputFile);
disposition.Size = new FileInfo(outputFile).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
smtp.Send(message);
link for ref:
https://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.attachments%28v=vs.110%29.aspx

EmailMessage message = new EmailMessage();
Recipient myrecipient = new Recipient("Gmail", "MyMail#gmail.com");
message.To.Add(myrecipient);
//Adding more To address
message.To.Add(myrecipient2);
message.To.Add(myrecipient3);
//Adding more CC address
message.Cc.Add(myrecipient4);
message.Cc.Add(myrecipient5);
//Adding more Bcc address
message.Bcc.Add(myrecipient6);
message.Bcc.Add(myrecipient7);
message.Subject = "test from Windows-Mobile";
message.BodyText = "this is the test from Windows-Mobile";
//Adding attachments
message.Attachments.Add("TextFilePath");
message.Send("Gmail");
MessagingApplication.Synchronize("Gmail");
SetForegroundWindow(this.Handle);

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

How attach mail template in .NET core

I am trying to attach the mail template in Mail Kit I am using .NET Core
here is my code
//From Address
string FromAddress = "info#gorollo.com";
string FromAdressTitle = "Gorollo";
//To Address
string ToAddress = email;
string Subject = subject;
string BodyContent = message;
var body = new BodyBuilder();
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress
(FromAdressTitle,
FromAddress
));
mimeMessage.To.Add(new MailboxAddress
(
ToAddress
));
mimeMessage.Subject = Subject;
using (var client = new SmtpClient())
{
client.Connect("smtp.mailgun.org", 587, false);
client.Authenticate(
"info#gorollo.com",
"password"
);
await client.SendAsync(mimeMessage);
await client.DisconnectAsync(true);
}
i saw many examples but not able to find the exact solution
so please anyone help me to sort out the problem
I have to attach Signup template in my mail here.
You're almost here. You can use the BodyBuilder to add text or HTML to the body. Either use the TextBody or HtmlBody property to set text or HTML respectively. Use the ToMessageBody() method to create a MimeEntity instance which you can use as the mail body.
Example:
var message = new MimeMessage();
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = "<h1>Hello, World!</h1>";
message.Body = bodyBuilder.ToMessageBody();

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

Insert image in email

I'm trying to insert an image in an email following this http://www.codeproject.com/Tips/326346/How-to-embed-a-image-in-email-body
but for some images are not showing in the mail.
Here is the code.
var message = new MailMessage();
message.From = new MailAddress("noreply#happy.com");
message.To.Add("testmail#gmail.com");
var body = new StringBuilder();
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
var path = #"C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg";
AlternateView altView = AlternateView.CreateAlternateViewFromString("testing mail: <img src=cid:myImage>", null, MediaTypeNames.Text.Html);
LinkedResource imageToSend = new LinkedResource(path);
imageToSend.ContentId = "myImage";
altView.LinkedResources.Add(imageToSend);
message.AlternateViews.Add(altView);
var smtp = new SmtpClient();
smtp.Send(message);

Adding an attachment to email using C#

I'm using the following code from this answer Sending email in .NET through Gmail. The trouble I'm having is adding an attachment to the email. How would I add an attachment using the code below?
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
The message object created from your new MailMessage method call has a property .Attachments.
For example:
message.Attachments.Add(new Attachment(PathToAttachment));
Using the Attachment class as proposed in the MSDN:
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
Correct your code like this
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);
http://csharp.net-informations.com/communications/csharp-email-attachment.htm
hope this will help you.
ricky
Hint: mail body is overwritten by attachment file path if attachment is added after, so attach first and add body later
mail.Attachments.Add(new Attachment(file));
mail.Body = "body";
A one line answer:
mail.Attachments.Add(new System.Net.Mail.Attachment("pathToAttachment"));

Categories