Send Email from worker role (Azure) with attachment in c# - email

I am trying to send an email(in c#) from worker role(Azure) with an attachment(from blob storage).
I am able to send an email but attachment(word document) is blank.
The following function is called from worker role.
public void sendMail(string blobName)
{
InitStorage();//Initialize the storage
var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
container = blobStorage.GetContainerReference("Container Name");
CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
if (File.Exists("demo.doc"))
File.Delete("demo.doc");
FileStream fs = new FileStream("demo.doc", FileMode.OpenOrCreate);
blob.DownloadToStream(fs);
Attachment attach = new Attachment(fs,"Report.doc");
System.Net.Mail.MailMessage Email = new System.Net.Mail.MailMessage("User#hotmail.com", "User#gmail.com");
Email.Subject = "Text fax send via email";
Email.Subject = "Subject Of email";
Email.Attachments.Add(attach);
Email.Body = "Body of email";
System.Net.Mail.SmtpClient client = new SmtpClient("smtp.live.com", 25);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("User#hotmail.com", Password);
client.Send(Email);
fs.Flush();
fs.Close();
Email.Dispose();
}
Please tell me where I am doing wrong?

I would try do fs.Position = 0; before attaching creating your Attachement object.
What's probably happening is that it's trying to read from current position in the stream and that stream is at the end, so it reads nothing.

Just a guess, but you should probably be calling fs.Close() before sending the email.

Related

How to implement Microsoft Graph deferred sending

I am trying to implement a deferred sending function to my site which currently sends email via Microsoft Graph. I have found some articles about SingleValueLegacyExtendedProperty being used to defer sending, but so far has been unsuccessful with it.
My current code just ignores the deferred sending time and sends the email immediately.
var message = new Message
{
Subject = Subject,
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = bodyText
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = recipient
}
}
},
};
message.SingleValueExtendedProperties = new MessageSingleValueExtendedPropertiesCollectionPage
{
new SingleValueLegacyExtendedProperty()
{
Id = "SystemTime 0x3FEF",
Value = DateTimeToSend.ToString("o")
}
};
var saveToSentItems = true;
await graphServiceClient.Me
.SendMail(message, saveToSentItems)
.Request()
.PostAsync();
In this article they suggest that the ID should be String {8ECCC264-6880-4EBE-992F-8888D2EEAA1D} Name pidTagDeferredSendTime when passing as JSON but it looks like that was not successful for other. I checked and can confirm that it did not work for me either.
Its important that the DateTime that you want the message to be sent is in UTC eg
"value": "2022-08-01T23:39:00Z"
Using local time won't work as Exchange does everything in UTC

How to send screenshot to any mail recipient using selenium

How can I send any screenshot captured using selenium web driver to a mail recipient?
In c# you can use
using Outlook1=Microsoft.Office.Interop.Outlook;
Add reference of Above
Outlook1.Application outlookApp1 = new Outlook1.Application();
Outlook1.MailItem mailItem = (Outlook1.MailItem)outlookApp1.CreateItem(Outlook1.OlItemType.olMailItem);
outlookApp1.CreateItem(Outlook1.OlItemType.olMailItem);
mailItem.Subject = "Your subject";
mailItem.To = "Email id";
mailItem.Importance = Outlook1.OlImportance.olImportanceLow;
mailItem.Display(false);
mailItem.Send();
You can even add attachments

How to insert data in to database when mail comes in inbox(mail server)

I have a requirement. I have a mail server where user sends mail with there requirement and i need to insert data in my database when mail arrive in mail box. i Have no idea about it. If anybody has any idea please share. Thanks in advance.
Please find the below codes for sending and receiving mails accordingly:
Send Mail
var message = new MailMessage("admin#bendytree.com", "someone#example.com");
message.Subject = "What Up, Dog?";
message.Body = "Why you gotta be all up in my grill?";`enter code here`
SmtpClient mailer = new SmtpClient("smtp.gmail.com", 587);
mailer.Credentials = new NetworkCredential("admin#bendytree.com","YourPasswordHere");
mailer.EnableSsl = true;
mailer.Send(message);
Recieving Mail
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("admin#bendytree.com", "YourPasswordHere");
var count = client.GetMessageCount();
Message message = client.GetMessage(count);
Console.WriteLine(message.Headers.Subject);
You can use this message object for database insertion.

Should I use the GRAPH API or a simple SMTP class to create an email ?

I don't seem to get it. I can create some code to send an email like this:
String userName = "user#domain.com";
String password = "your password";
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("ToAddress"));
msg.From = new MailAddress(userName);
msg.Subject = "Test Office 365 Account";
msg.Body = "Testing email using Office 365 account.";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Host = "smtp.office365.com";
client.Credentials = new System.Net.NetworkCredential(userName, password);
client.Port = 587;
client.EnableSsl = true;
client.Send(msg);
Or I can create an app in our Azure AD and set the permissions and send an email with the GRAPH API right?
Is there any possible reason I would want to use the GRAPH API to do this ?
Well you're asking for an opinion, so it's hard to give an all-inclusive answer. However, one reason that you might prefer Graph over SMTP is that it uses OAuth, so you do not need to ask for or store the user's username or password.

Saving mail into Sent items in JavaMail

I am using something like the following to save a copy of the sent message in the user Sent folder in JavaMail. It works fine for emails with no attachment and for emails whose attachments are less than 1MB. But program stops before the code is actually executed for attachments greater than 1MB. Any idea how to deal with this one?
String host = ReadConfigPropertiesFile.getPropertyValue("server.host");
String smtpHost = ReadConfigPropertiesFile.getPropertyValue("smtp.host");
String from = "test#myserver.net";
String to = "test#myserver.net";
// Get system properties
Properties properties = System.getProperties();
// Setup smtp mail server
properties.setProperty(smtpHost, host);
properties.setProperty("mail.mime.encodeparameters", "true");
// properties.setProperty("mail.mime.decodeparameters","true");
properties.setProperty("mail.mime.encodefilename", "true");
// properties.setProperty("mail.mime.decodefilename","true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Peace ", "UTF-8");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message body
messageBodyPart.setContent("Hello attachment", "text/html; charset=UTF-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
String[] filename = {"C:/Users/Dake/Desktop/music.mp3"};
for (int i = 0; i < filename.length; i++) {
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename[i]);
messageBodyPart.setDataHandler(new DataHandler(source));
// messageBodyPart.setFileName(filename[i]);
//messageBodyPart.setHeader("Content-Type", "text/plain; charset=UTF-8; name="+MimeUtility.encodeText(filename[i]));
// messageBodyPart.setHeader("Content-ID", filename[i]);
messageBodyPart.setFileName(MimeUtility.encodeText(filename[i], "UTF-8", null)); //encode filename
//bodyPart.setFileName(MimeUtility.encodeText(attachment.getName(), "UTF-8", null));
multipart.addBodyPart(messageBodyPart);
}
// Put parts in message
message.setContent(multipart);
//set the time
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:MM:SS");
Date date = new Date();
String sentDate = df.format(date);
Date dd = (Date) df.parse(sentDate);
message.setSentDate(date);
// Send the message
Transport.send(message);
System.out.println("Message sent...");
// Copy message to "Sent Items" folder as read
Store store = session.getStore("imap");
store.connect(host, "user", "userpwd");
Folder folder = (Folder) store.getFolder("Sent");
if (!folder.exists()) {
folder.create(Folder.HOLDS_MESSAGES);
}
folder.open(Folder.READ_WRITE);
System.out.println("appending...");
// folder.appendMessages(new Message[]{message});
try {
folder.appendMessages(new Message[]{message});
// Message[] msgs = folder.getMessages();
message.setFlag(FLAGS.Flag.RECENT, true);
} catch (Exception ignore) {
System.out.println("error processing message " + ignore.getMessage());
} finally {
store.close();
// folder.close(false);
}
System.out.println("Msg send and saved ....");
}
When I run the above code, it displays the appending.... and it stops there forever. And I am using Apache James server 3.0-beta4 as the mail server.
Is your server breaking the connection because it's taking too long to send the message to be appended? (If so, how long is it taking?)
Or is the server breaking the connection because it won't allow you to append a message that large?
Do you get any useful information from the server in the debug output?
I know this is a old question, but maybe this helps you or some others.
I guess the problem of your code is that you try to manipulate the Recent-Flag: message.setFlag(FLAGS.Flag.RECENT, true);. According to the IMAP-Standard the Recent-Flag can't be altered by clients.