I can send emails using the method when not using hangfire.
When the method is called from hangfire it is shown as succeeded but the email doesnt send.
BackgroundJob.Schedule(
() => Email(Subject),
TimeSpan.FromMinutes(1)
);
public void Email(string Subject)
{
try
{
//Initialize WebMail
WebMail.SmtpServer = "relay.example.com";
WebMail.SmtpPort = 587;
WebMail.SmtpUseDefaultCredentials = false;
WebMail.UserName = "xxxx";
WebMail.Password = "xxxx";
WebMail.From = "\"Reports\" <Reports@example.com>";
//Send Email
WebMail.Send(to: "client@example.com",
subject: Subject,
body: "Test Email"
);
}
catch (Exception e)
{
}
}
The username, password, and relay service have been removed for security as has the actual email addresses.
I have gone and removed the try/catch blocks to see if there are any errors produced. Normally, It succeeds as before but occasionally it will throw the following error.
System.NullReferenceException
Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.WebPages.Scope.AspNetRequestScopeStorageProvider.get_RequestScopeInternal()
at System.Web.WebPages.Scope.AspNetRequestScopeStorageProvider.get_CurrentScope()
at System.Web.Helpers.WebMail.set_SmtpServer(String value)
at Email(String Subject)
I have then attempted the version that allows for type passing.
BackgroundJob.Schedule<WebMail>(
() => Email(Subject),
TimeSpan.FromMinutes(1)
);
However that throws a compiler error about using a static type.
Thanks for any help guys.
EDIT:
Still open to better options. However I did find a cheeky work around. I was able to get this to work by creating a method that fires a post request to a page to actually send the email. Whereas Hangfire just activates the post request.
EDIT: NVM workaround was a false positive due to an extra line that was left in from testing