SmtpMail.Send() doesn't work - c#

i have a problem with send mail in c#; it doesn't send any mail and also doesn't throw any exceptions with failure :
using System.Web.Util;
public static void SendEmail(string _FromEmail, string _ToEmail, string _Subject, string _EmailBody)
{
// setup email header .
SmtpMail.SmtpServer = "localhost";
MailMessage _MailMessage = new MailMessage();
_MailMessage.From = _FromEmail;
_MailMessage.To = _ToEmail;
_MailMessage.Subject = _Subject;
_MailMessage.Body = _EmailBody;
try
{
SmtpMail.Send(_MailMessage);
}
catch (Exception ex)
{
throw new ApplicationException("error has occured: " + ex.Message);
}
}
please help!

Check the folders in your IIS' Mailroot directory (probably located in C:\InetPub\Mailroot). Chances are your mails are dropped there, probably in the Badmail or the Queue directory.

see C:\InetPub\Mailroot\queue folder. if your emails got stuck in this folder then
1>> stop your SMTP
2>> move emails from queue folder to C:\inetpub\mailroot\Pickup folder and start your smtp server and wait for few seconds.
if your email got stuck in queue folder again then you need to enable smtp logging for more information. use this link to see how to enable smtp logging.
http://www.msexchange.org/tutorials/Logging_the_SMTP_Service.html

Related

Can someone help me understand this exception? System.InvalidOperationException: ReferenceAttachment header is corrupt

I'm using aspose.email to automate the process of migrating emails. For only one of the accounts, I'm getting this exception:
System.InvalidOperationException: ReferenceAttachment header is corrupt
at   .    (IAsyncResult )
at   .     ()
at Aspose.Email.Clients.Imap.ImapClient.Backup(IConnection connection, ImapFolderInfoCollection folders, String fileName, BackupSettings options)
at pst_creator.Program.GetEmails() in C:\Users\process.control\source\pst\AlexPST\AlexPST\Program.cs:line 103
Here's the relevant code:
private void GetEmails() //Downloads emails from IMAP server
{
ImapFolderInfoCollection infos = new ImapFolderInfoCollection();
try
{
foreach(string folder in folders)
{
infos.Add(client.GetFolderInfo(folder));
}
client.Backup(infos, $"{pstPath}{client.Username.Replace(accountSuffix, "")}.pst", BackupOptions.Recursive);
logger.Log($"SUCCESS - .pst created for {client.Username}");
}
catch (Exception ex)
{
logger.Log(Environment.NewLine + ex);
}
}
I'm assuming in the users mailbox theres a corrupted inline attatchment. Is there a way I can bypass this error? I would like to be able to skip over corrupted emails.

C# and EWS How to Save Message as an Email Instead of a Draft

What I have done so far is to connect to EWS, access my inbox, create an item (email) with some info in Body, Subject, From, and To, save it to the Draft folder, and finally move it to my inbox. It works, however, I get a draft in the inbox instead of an email.
Is it possible to get the message as an email with the above scenario and how can I achieve that?
Below is my code. Any input would be very appreciated.
try {
message.Save();
}
catch(Exception e21) {;
}
message.Load(PS);
message.From = new EmailAddress("someone#abc.com");
message.ToRecipients.Add("me#abc.com");
message.Body = "This is A test take 1";
message.Subject = "Testing to send as someone else...";
// add in the attachments......
message.Update(ConflictResolutionMode.AlwaysOverwrite); // require this here why????
message.Copy(theTempFolder.Id); // get the item as a draft in my mailbox instead of an email
}
catch(Exception e99) {
Console.WriteLine("Exception fail to connect to office 365 on the cloud: " + e99.Message);
}
You need to set the MessageFlags property https://learn.microsoft.com/en-us/office/client-developer/outlook/mapi/pidtagmessageflags-canonical-property to 1 (before you call update) eg
ExtendedPropertyDefinition PR_MESSAGE_FLAGS_msgflag_read = new ExtendedPropertyDefinition(3591, MapiPropertyType.Integer);
message.SetExtendedProperty(PR_MESSAGE_FLAGS_msgflag_read, 1);
Which will then make the message look like it was received. The other way is just import an EML like https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-import-items-by-using-ews-in-exchange
Have you tried to send it to yourself with either message.Send() or message.SendAndSaveCopy() ? see more here

Programmatically moving items from Junk folder to Inbox in Outlook.Interop class?

I am currently refining an MS Outlook Add-In to pick up emails that end up in the Junk folder with "legit" addresses and then moving them into the Inbox folder.
This is an occurence that happens a lot for Gmail addresses, and is a bit painstaking for our staff members, who have to manually link those emails to their client accounts.
Has anyone attempted this? I have registered the incoming email event handler to read the Junk folder when an email comes in, but I keep getting an exception. I suspect it has to do with the fact that some of these emails are spam; which simply means that the MailItem will have lots of errors.
Has anyone had the same issue? Here is my code:
public void OutlookApplication_ItemReceived(string entryID)
{
//this.outlookNameSpace = this.application.GetNamespace("MAPI");
//Outlook.MAPIFolder inbox = this.outlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
//Outlook.MAPIFolder junkFolder = this.outlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderJunk);
if (Properties.Settings.Default.AutoLink || Properties.Settings.Default.EnableLeadLoader)
{
Outlook.MailItem mail = null;
try
{
this.Log("Email detected: incoming");
mail = this.application.Session.GetItemFromID(entryID) as Outlook.MailItem;
this.leadLoaderRecipient = Properties.Settings.Default.LeadLoaderRecipient.ToLower();
Outlook.Recipients recips = mail.Recipients; //That's where its crashing as the object is null... if read from spam folder
foreach (Outlook.Recipient recip in recips)
{
Outlook.PropertyAccessor pa = recip.PropertyAccessor;
string smtpAddress = pa.GetProperty(PR_SMTP_ADDRESS).ToString();
if (Properties.Settings.Default.EnableLeadLoader)
{
if (smtpAddress.ToLower() == this.leadLoaderRecipient)
this.ProcessLead(mail);
}
}
if (Properties.Settings.Default.AutoLink)
{
this.AutoLink(mail, true);
}
}
catch (Exception ex)
{
this.Log("Exception (ItemReceived): " + ex.ToString());
}
finally
{
if (mail != null)
{
Marshal.ReleaseComObject(mail);
}
}
}
}
Looking forward to your thoughts guys! :) TIA!
When exactly does your code run? Is that an Application.NewMailEx event handler? What is the exception?
Try to use the Items.ItemAdd event on the Junk Mail folder instead of using Application.NewMailEx.

How to email large files using c# windows application

I'm developing an windows application in which i need to send some files as attachment through email.
Code
public string SendMail(string mFrom,
string mPass,
string mTo,
string mSub,
string mMsg,
string mFile,
bool isDel)
{
string sql = "";
try
{
System.Net.Mail.MailAddress mailfrom = new System.Net.Mail.MailAddress(mFrom);
System.Net.Mail.MailAddress mailto = new System.Net.Mail.MailAddress(mTo);
System.Net.Mail.MailMessage newmsg = new System.Net.Mail.MailMessage(mailfrom, mailto);
newmsg.IsBodyHtml = false;
if (mFile.Length > 2
&& File.Exists(mFile))
{
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(mFile);
newmsg.Attachments.Add(att);
}
newmsg.Subject = mSub;
newmsg.Body = mMsg;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(mFrom, mPass);
smtp.EnableSsl = true;
smtp.Send(newmsg);
newmsg.Dispose();
GC.Collect();
sql = "OK";
if (isDel
&& File.Exists(mFile))
{
File.Delete(mFile);
}
}
catch (Exception ex)
{
sql = ex.Message;
}
return sql;
}
This code works fine for small files.But i need to send large files up to 1-2 GB.
For that what to do.
You cannot use e-mail to get these files across and this has nothing to do with your code.
I don't think there is ANY provider out there who will support sending files of that size let alone receiving them. Even G-Mail has a limit of 25 Mb which is quite large already.
E-Mail is not the proper channel to do this.
So the problem will not be in your code, the provider will limit the size of the attachment and just refuse them when you present them with a larger file. You will get an e-mail back at your FROM address stating that the file is too large and your e-mail did not get across.
For doing this in the simplest form probably look at FTP.
I do agree with Gerald Versluis in that email is not the proper channel for this. Even if you are using your own email server that is configurable there is probably some internal limit that prevents it from sending such big files.
I’d go with FTP for this but if you really want to continue with email I’d suggest you check following first.
Is there connection timeout property on the server? If yes then try to increase it to 3 hours or something like that.
Is there enough space on the mail server?
Is there some documentation for your email server? Are there any additional details regarding attachment size ?

Notify C# Client, when SMTP Server receive a new Email

I want to get all emails in my ASP.NET application that have a certain CC-recipient. To use this for future emails I didn't want to polling all the time to get them. But I can't find a way, how I can use push to get the emails instantly. Are their any frameworks in C# to help me for this?
I want to connect with my application to a mail server and register a method 'X'. Always when a new message arrived to the mail server, my application have to be notified and my application should execute the method 'X'.
I hope that this is possible with code like this:
void Application_Start()
{
...
ConnectWithTheSmtpServer();
RegisterMethodForNotification(DoSomethink);
...
}
void DoSomethink(Mail newMail)
{
// Do Somethink with the mail
}
EDIT:
I did it with the MailSystem.Net. It works very fine and is very easy to implement.
Sample Code:
void Application_Start()
{
var worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(StartIdleProcess);
if (worker.IsBusy)
worker.CancelAsync();
worker.RunWorkerAsync();
}
private void StartIdleProcess(object sender, DoWorkEventArgs e)
{
if (_imap != null && _imap.IsConnected)
{
_imap.StopIdle();
_imap.Disconnect();
}
_imap = new Imap4Client();
_imap.ConnectSsl(server-name, 993);
_imap.Login(username, passwort);
var inbox = _imap.SelectMailbox("INBOX");
_imap.NewMessageReceived += new NewMessageReceivedEventHandler(NewMessageReceived);
inbox.Subscribe();
_imap.StartIdle();
}
public static void NewMessageReceived(object source, NewMessageReceivedEventArgs e)
{
// Do something with the source...
}
You are approaching this from the wrong angle.
SMTP does not support receiving mail (never mind PUSH mail). POP3 is what you can use for retrieving mail, but it does not have support for PUSH either (so you would have to pull for mail).
The IMAP4 IDLE extension is what most refer to as PUSH mail - so you will need to find a library for C# that supports IMAP4 IDLE. I found some information that will get you going in the right direction (no reason to duplicate it here):
Using C# .Net Libraries to Check for IMAP Messages
Accessing IMAP in C#
Keep in mind when choosing a solution that it needs to support IDLE.
I really like the look of MailSystem.Net as it fulfills your requirements.
Remember that your mail server also needs to have IMAP4 and IMAP4 IDLE enabled. Some mail servers don't support it, so you might be clean out of luck (and will have to use POP3 pulling).
You could send a copy of your emails(i.e. using /etc/aliases file in PostFix) to a MAIL SERVER YOU CAN HANDLE. Once there, you can implement a MAIL PROCESSOR that do whatever you want anytime a mail that MEET CERTAIN CONDITIONS arrives.
Hope that helps,
You can try this:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace
namespace receiveemail
{
class Program
{
static void Main(string[] args)
{
// Create a folder named "inbox" under current directory
// to save the email retrie enter code here ved.
string curpath = Directory.GetCurrentDirectory();
string mailbox = String.Format("{0}\\inbox", curpath);
// If the folder is not existed, create it.
if (!Directory.Exists(mailbox))
{
Directory.CreateDirectory(mailbox);
}
// Gmail IMAP4 server is "imap.gmail.com"
MailServer oServer = new MailServer("imap.gmail.com",
"gmailid#gmail.com", "yourpassword", ServerProtocol.Imap4 );
MailClient oClient = new MailClient("TryIt");
// Set SSL connection,
oServer.SSLConnection = true;
// Set 993 IMAP4 port
oServer.Port = 993;
try
{
oClient.Connect(oServer);
MailInfo[] infos = oClient.GetMailInfos();
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
// Download email from GMail IMAP4 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an email file name based on date time.
System.DateTime d = System.DateTime.Now;
System.Globalization.CultureInfo cur = new
System.Globalization.CultureInfo("en-US");
string sdate = d.ToString("yyyyMMddHHmmss", cur);
string fileName = String.Format("{0}\\{1}{2}{3}.eml",
mailbox, sdate, d.Millisecond.ToString("d3"), i);
// Save email to local disk
oMail.SaveAs(fileName, true);
// Mark email as deleted in GMail account.
oClient.Delete(info);
}
// Quit and purge emails marked as deleted from Gmail IMAP4 server.
oClient.Quit();
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}

Categories

Resources