StmpClient use works for remote users via VPN but not for users in office, on the network - smtp

I've implemented the .NET SmtpClient to send emails programmatically. Multiple users of the application and at various stages, an email is automatically sent. For users that are running the application from home, over VPN, the email almost always works. For users at the office, the email fails, "Failure sending mail" is exception message with no inner exception. The email server is MS Exchange, for large financial institution. Not using SSL, using port 25.
SmtpClient mailClient = new SmtpClient (getSmtpServer(), getSmtpPort());
mailClient.Timeout = 20000;
mailClient.UseDefaultCredentials = true;
MailAddress from = new MailAddress ( getSmtpFromAcct(),
"My Application",
System.Text.Encoding.UTF8);
MailAddress to = new MailAddress ( toEmail );
MailMessage message = new MailMessage(from, to);
for( int i = 1; i < toUsers.Count; i++)
{
BeanUser beanUser = toUsers[ i ];
message.To.Add( beanUser.getEmail() );
}
message.Subject = subject;
message.Body = messageBody;
mailClient.Send(message);

Related

how to send mail from group email in script task ssis

I want to send email from SSIS. To do this I am using script task and inside that, i am using below code and same is working very well.
Now my manager told me to send mail from team_dev#uhg.com instead of hieko#uhg.com.I this case what would be my password as team_dev#uhg.com is group email.
email.From = new MailAddress("hieko#uhg.com");
email.To.Add("team_testing#uhg.com");
email.Subject = "Test Mail";
email.Body = "This Email is coming from SSIS Script Task";
try
{
MailMessage email = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("alaska");
// START
email.From = new MailAddress(SendMailFrom);
email.To.Add(SendMailTo);
email.Subject = SendMailSubject;
email.Body = SendMailBody;
//END
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential(SendMailFrom, "my password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(email);
MessageBox.Show("Email was Successfully Sent ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Dts.TaskResult = (int)ScriptResults.Success;

SMTP is not sending emails in gmail business account

This code is working well in gmail personal account, but when I try to use gmail business account, it is not working and keeps giving an error. 5.5.1 Authentication Required.
void SendEmail()
{
DataTable data = GetData();
DataTable email_data = GetEmailData();
data.TableName = "Employee_Data";
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(data);
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
String from = "seong#abcd.net";
for (int i = 0; i < email_data.Rows.Count; i++)
{
String to = email_data.Rows[i][0].ToString();
using (MailMessage mm = new MailMessage(from, to))
{
mm.Subject = "Employees Attachment";
mm.Body = "Employees Exported Attachment";
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "Employees.xlsx"));
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
credentials.UserName = "seong#abcd.net";
credentials.Password = "1234";
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
}
}
}
}
}
I solved this problem.
The account should not use 2nd verification in gmail if you want to use SMTP.
https://support.google.com/accounts/answer/1064203?hl=en&ref_topic=7189195
I can't control those things, I ask the administrator allow not to use 2nd verification.
So I can work with that account using SMTP.
Smtp method for Business Gsuite
require_once('class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Port = 587;
$mail->Host = "smtp.gmail.com";
$mail->Username = "Enter the user ID"; // SMTP account username
// SMTP account password
$mail->Password = "Enter your password";
$mail->SetFrom('Enter the User ID', 'Subject');
$mail->AddReplyTo("Enter the User ID", "Subject");
$mail->AddAddress($to, "Name");
$mail->Subject = "Contact Enquiry";
$message = '';
$mail->MsgHTML($message);
if($mail->Send()){
$mail->ClearAddresses();
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
} else {
echo "Mailer Error: " . $mail->ErrorInfo;
}

ASP.Net 2013 MVC 5 insert record and sends email with link to the record just created

I have setup an asp.net MVC project that inserts a record and then grabs the url information to be sent via email of which is a link in the body of the email. I would like to be able to pass the location of the details page with the id of the record if that makes sense? I am just not sure how to capture the full path and the id that I just created in the insert of the record just submitted. Can any one please help me on this. It would be greatly appreciated. This is my code and I need the url and id to be in the body of the email upon submit:
[HttpPost]
public ActionResult NewHire([Bind(Include = "ID,Manager,HR_Emp,Emp_FirstName,Emp_LastName,Emp_StartDate,Emp_OfficeLocation,Emp_Department,Emp_Title")] NewHire newhire)
{
if (ModelState.IsValid)
{
_entities.NewHires.Add(newhire);
_entities.SaveChanges();
MailMessage mail = new MailMessage();
mail.To.Add("Stephen.Michaels#brixmor.com");
mail.From = new MailAddress("someone#somewhere.com");
mail.Subject = "Test";
string Body = "<a href=http://www.google.com>" + "Click for Record" + "</a>";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "test";
smtp.Port = 25;
smtp.Send(mail);
return RedirectToAction("NewHire");
}
return View(newhire);
}
I would suggest you to use the Url.Action
if (ModelState.IsValid)
{
_entities.NewHires.Add(newhire);
_entities.SaveChanges();
string url = Url.Action("ActionName", "ControllerName", newhire.id);
MailMessage mail = new MailMessage();
mail.To.Add("Stephen.Michaels#brixmor.com");
mail.From = new MailAddress("someone#somewhere.com");
mail.Subject = "Test";
string Body = "<a href='"+ url +"'>" + "Click for Record" + "</a>";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "test";
smtp.Port = 25;
smtp.Send(mail);
return RedirectToAction("NewHire");
}

The request failed with HTTP status 401: Unauthorized. SSRS

I have a class in a MVC web project that processes SSRS.
When I run the app in the IIS machine I access the reports OK.
When run from another machine on the network gives me "The request failed with HTTP status 401: Unauthorized."
The Report Server has own unique credentiais. Does not accept the logon credentials on the network
Annex a part of the class
reportViewer.ProcessingMode = ProcessingMode.Remote;
reportViewer.ServerReport.ReportServerUrl = new Uri(System.Configuration.ConfigurationManager.AppSettings["RSUrl"]);
reportViewer.PromptAreaCollapsed = true;
reportViewer.ShowParameterPrompts = false;
reportViewer.SizeToReportContent = true;
reportViewer.InteractivityPostBackMode = InteractivityPostBackMode.AlwaysAsynchronous;
reportViewer.AsyncRendering = false;
if (reportType == "GRP")
{
reportViewer.ShowToolBar = false;
reportViewer.ShowPageNavigationControls = false;
}
else //if (reportType == "RPT")
{
reportViewer.ShowToolBar = true;
reportViewer.ShowPageNavigationControls = true;
}
strReportName = _reqObjNm;
strReportPath = System.Configuration.ConfigurationManager.AppSettings["RSPath"];
reportViewer.ServerReport.ReportPath = strReportPath + strReportName;
string RSUsername = System.Configuration.ConfigurationManager.AppSettings["RSUserName"];
string RSPwd = System.Configuration.ConfigurationManager.AppSettings["RSPwd"];
string RSDomain = System.Configuration.ConfigurationManager.AppSettings["RSDomainFull"];
//App_Start.ReportViewerCredentials rvCreds = new App_Start.ReportViewerCredentials(RSUsername, RSPwd, RSDomain);
//reportViewer.ServerReport.ReportServerCredentials = rvCreds;
reportViewer.Visible = true;
if (reportViewer.ServerReport.GetParameters().Count > 0) // HERE breaks :(
If I understand your question correctly I think you need to add a "ReportUser" to the remote SSRS server as a local user and in SSRS manager grant the local "ReportUser" user account proper access.

EWS - Attachment Not Sent With Invitation

I am facing an issue with sending attachments with invitation using EWS Managed API. Appointments attendees are not receiving any attachments added to the appointment but
attachment do appears in the calendar of the person that created the appointment.
Here is my code snippet:
try
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
service.Credentials = new WebCredentials("calendar_user", "password1", "acme");
service.Url = new Uri("https://acme.com/EWS/Exchange.asmx");
Appointment appointment = new Appointment(service);
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "tin.tin#acme.com");
String UID = "D09F3FF6-1461-414C-89E8-C05BC3B66A4A";
appointment.ICalUid = UID;
appointment.Subject = "Test Subject";
appointment.Body = "Test Content.";
appointment.Start = new DateTime(2012, 07, 11, 17, 00, 0);
appointment.End = appointment.Start.AddMinutes(30);
FileAttachment attachment = appointment.Attachments.AddFileAttachment(#"C:\Users\tintin\Documents\Test.xlsx");
attachment.IsInline = false;
appointment.RequiredAttendees.Add("tin.tin#acme.com");
appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
}
catch (Exception ex)
{
}
Look like EWS has horrible limitation with attachment handling. I found a workaround to resolve this issue which requires updating appointment object twice.
appointment.ICalUid = UID;
appointment.Subject = "Test Subject";
appointment.Body = "Test Content.";
appointment.Start = new DateTime(2012, 07, 11, 17, 00, 0);
appointment.End = appointment.Start.AddMinutes(30);
FileAttachment attachment = appointment.Attachments.AddFileAttachment(#"C:\Users\tintin\Documents\Test.xlsx");
attachment.IsInline = false;
appointment.Save(folderCalendar, SendInvitationsMode.SendToNone);
appointment.RequiredAttendees.Add("tin.tin#acme.com");
appointment.Update(ConflictResolutionMode.AutoResolve, SendInvitationsOrCancellationsMode.SendToAllAndSaveCopy);
Looks like this issue is specific to Exchange Server 2010 Service Pack 1. I got similar issue and when I changed the version to SP2 issue got resolved. Below code solved the problem
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
A second update did the trick, but it will cause a cancelled meeting at the bottom. Can't use it in product.
It doesn't work to change the version to SP2.
Still find a better solution.
Yes, EWS has some issue, while updating the meeting with new attachments it is not getting updated for the first time. Needed 2 instances to update it.
Microsoft.Exchange.WebServices.Data.Appointment meet1 = await
Microsoft.Exchange.WebServices.Data.Appointment.Bind(service, strMessageID);
meet1.Attachments.Clear();
foreach (FileUpload Item in
objCreateEvent.strAttachmentUploadPath)
{
meet1.Attachments.AddFileAttachment(Item.fileName,
Item.filePath);
}
meet1.RequiredAttendees.Clear();
foreach (string ToItem in objToIds)
{
meet1.RequiredAttendees.Add(ToItem);
}
await
meet1.Update(ConflictResolutionMode.AlwaysOverwrite,
SendInvitationsOrCancellationsMode.SendToAllAndSaveCopy);
Microsoft.Exchange.WebServices.Data.Appointment
meeting2 = await Microsoft.Exchange.WebServices.Data.Appointment.Bind(service,
strMessageID);
meeting2.Attachments.Clear();
foreach (FileUpload Item in
objCreateEvent.strAttachmentUploadPath)
{
meeting2.Attachments.AddFileAttachment(Item.fileName, Item.filePath);
}
meeting2.RequiredAttendees.Clear();
foreach (string ToItem in objToIds)
{
meeting2.RequiredAttendees.Add(ToItem);
}
await
meeting2.Update(ConflictResolutionMode.AlwaysOverwrite,
SendInvitationsOrCancellationsMode.SendToAllAndSaveCopy);