I am trying to automate sending emails with multiple lines and paragraphs through excel using VBA. Here is the code I have so far:
Sub Send_Email()
Dim Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body As String
Dim Mail_Object, Mail_Single As Variant
Email_Subject = "test"
Email_Send_From = "email"
Email_Cc = ""
Email_Bcc = ""
Dim r As Range, cell As Range, mynumber As Long
Dim i As Long
Set r = Range("K2:K300")
i = 2
For Each cell In r
If Cells(i, "K").Value = "" Then
Else
Email_Send_To = Worksheets("Sheet1").Cells(i,"K").Value
Email_Body = "test from outlook excel"
Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)
With Mail_Single
.Subject = Email_Subject
.To = Email_Send_To
.cc = Email_Cc
.BCC = Email_Bcc
.Body = Email_Body
.send
End With
End If
i = i + 1
Next
On Error GoTo debugs
debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub
However I'm not sure how to make the body of the email include line breaks and split up paragraphs rather than just having one block of text.
Use VBNewLine for a new line character.
Dim A As String: A = "Line A"
Dim B As String: B = "Line B"
Debug.print(A & VbNewLine & B)
Output:
Line A
Line B
Related
Hi trying to add a newline between my body content after paste a table and signature,codes are below:
dim FileName As String
Dim filepath As String
Dim rng As Range
Dim OutlookApp As Object
Dim Outlookmail As Object
Dim lastrowo As Integer
Application.ScreenUpdating = False
Set OutlookApp = CreateObject("Outlook.Application")
Set Outlookmail = OutlookApp.CreateItem(0)
lastrowo = Worksheets("Price And Accrued Info").Range("K550").End(xlUp).row
Set rng = Worksheets("Price And Accrued Info").Range("K2:y" & lastrowo)
rng.Copy
Dim vInspector As Object
Set vInspector = Outlookmail.GetInspector
Dim wEditor As Object
Set wEditor = vInspector.WordEditor
With Outlookmail
.To = ""
.cc=""
.Subject = "UNCONFIRMED TRADES AS OF " & Format$(Date, "YYYY.MM.DD")
wEditor.Paragraphs(1).Range.Text = "Hi The following trades are unconfirmed trades."
wEditor.Paragraphs(2).Range.Paste
wEditor.Paragraphs(4).Range.Text = vbNewLine & "<br>"
.display
' .attachments.Add drWorkbook.FullName
' .attachments.Add crWorkbook.FullName
'
End With
Set Outlookmail = Nothing
Set OutlookApp = Nothing
Application.ScreenUpdating = True
Try this:
With Outlookmail
.To = ""
.cc = ""
.Subject = "UNCONFIRMED TRADES AS OF " & Format$(Date, "YYYY.MM.DD")
wEditor.Paragraphs(1).Range.Text = "Hi The following trades are unconfirmed trades." _
& String(5, vbNewLine)
wEditor.Paragraphs(5).Range.Text = "This is is the last line." _
& vbNewLine & vbNewLine
wEditor.Paragraphs(3).Range.Paste
.display
End With
I am trying to add an attachment functionality to my emails. My email code is working however the attachments are being sent as ATT00001.bin files.
The variable Forms![frmMain]!TabCtl54.Pages("page56").Controls("subtblcontent").Form![attachmentlnk] is a textbox on a form which is where I would put my file name.
attachmentlnkvar = "file:///C:/Users/desktopname/Desktop/" & Forms![frmMain]!TabCtl54.Pages("page56").Controls("subtblcontent").Form![attachmentlnk] & ".pdf"
With cdomsg
.To = emailstr
.FROM = fromemailstr
.subject = Forms!frmMain.txtSubject
.Attachments.Add attachmentlnkvar
.HTMLBody = strHTML
.Send
End With
Set cdomsg = Nothing
Is there a way I can send my files as pdfs?
I am happy to share with you the function which I use to sent all my emails:
Public Sub SendMessage(Optional SubjectText = "", Optional BodyText = "", Optional AttachmentPath = "", Optional sendTo = "", Optional sendCC = "", Optional DeliveryConfirmation = True, Optional DisplayDoNotAutoSend = True, Optional SendHighPriority = True, Optional UseHTML = True)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Dim MultipleAttachmentPath As String
Dim CurrentAttachment As Variant
Dim aAtachments() As String
On Error GoTo ErrorMsgs
DoCmd.Hourglass True
' Create the Outlook session.
Set objOutlook = New Outlook.Application
' Create the message.
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
If UseHTML Then
.BodyFormat = olFormatHTML
End If
If Not isnull(sendTo) And InStr(sendTo, "#") > 0 Then
.To = sendTo
End If
If Not isnull(sendCC) And InStr(sendCC, "#") > 0 Then
.CC = sendCC
End If
.Subject = SubjectText
If UseHTML Then
.HTMLBody = "<div style='font-family:Calibri,sans-serif'>" & BodyText & GetThankYouSignature & "</div>"
Else
.Body = BodyText & vbCrLf & GetUserFullNameInASCIIText & vbCrLf & vbCrLf
End If
If SendHighPriority Then
.Importance = olImportanceHigh 'High importance
End If
If DeliveryConfirmation Then
.OriginatorDeliveryReportRequested = True
.ReadReceiptRequested = True
End If
On Error Resume Next
If AttachmentPath <> "" Then
' Add attachments to the message.
If Not IsMissing(AttachmentPath) And InStr(AttachmentPath, ";") = 0 Then
Set objOutlookAttach = .Attachments.add(AttachmentPath)
ElseIf Not IsMissing(AttachmentPath) And InStr(AttachmentPath, ";") > 0 Then
aAtachments = Split(AttachmentPath, ";")
For Each CurrentAttachment In aAtachments
.Attachments.add (CurrentAttachment)
Next
End If
End If
On Error GoTo ErrorMsgs
End With
If DisplayDoNotAutoSend Or isnull(sendTo) Then
objOutlookMsg.Display
Else
objOutlookMsg.Send
End If
Set objOutlookMsg = Nothing
Set objOutlook = Nothing
Set objOutlookRecip = Nothing
Set objOutlookAttach = Nothing
DoCmd.Hourglass False
Exit Sub
ErrorMsgs:
DoCmd.Hourglass False
If Err.Number = "287" Then
MsgBox "You clicked No to the Outlook security warning. " & _
"Rerun the procedure and click Yes to access e-mail" & _
"addresses to send your message. For more information," & _
"see the document at http://www.microsoft.com/office" & _
"/previous/outlook/downloads/security.asp. "
Else
Call LogError(Err.Number, Err.Description, "SystemUtilities", "SendMessage")
Resume Next
Resume
End If
End Sub
The variable AttachmentPath can contain multiple paths to attachments delimited by ";"
Don't use file:// etc., just the path. And backslashes.
attachmentlnkvar = "C:\Users\desktopname\Desktop\" & Forms![frmMain]!TabCtl54.Pages("page56").Controls("subtblcontent").Form![attachmentlnk] & ".pdf"
Instead of .Attachments.Add attachmentlnkvar have you tried .AddAttachment attachmentlnkvar? That's what I use to send PDF reports via an SMTP server instead of Outlook.
The problem is with your SMTP server. Try putting the attachment after the body to avoid this problem. If that doesn't work, try sending the message as plain text instead of HTML using:
.TextBody = bodyText
EXAMPLE:
attachmentlnkvar = "C:/Users/desktopname/Desktop/" & Forms![frmMain]!TabCtl54.Pages("page56").Controls("subtblcontent").Form![attachmentlnk] & ".pdf"
With cdomsg
.To = emailstr
.FROM = fromemailstr
.Subject = Forms!frmMain.txtSubject
.HTMLBody = strHTML
.AddAttachment attachmentlnkvar
.Send
End With
Set cdomsg = Nothing
EXPLANATION:
https://kb.mit.edu/confluence/pages/viewpage.action?pageId=4981187
I have a macro which the idea is to create an Outlook email from a textbox that I have in excel.
The problem is when I write a word and put a hyperlink on it, when the email is displayed, the hyperlink is not there.
Sub Envio()
Dim endereco, arquivo, destino, assunto, mensagem, nome, copia, anexo As String
Dim row, report As Integer
Dim i As Integer
Dim OutApp As Outlook.Application
Dim outMail As Outlook.MailItem
anexo = ThisWorkbook.Sheets("Mensagem").Cells(39, 2).Value
assunto = ThisWorkbook.Sheets("Mensagem").Cells(5, 2).Value
mensagem = ThisWorkbook.Sheets("Mensagem").[TextBox].Text & vbCrLf
copyblind = ThisWorkbook.Sheets("Mensagem").Cells(8, 2).Value
i = 2
destino = ThisWorkbook.Sheets("Emails").Cells(i, 1).Value
Do Until destino = ""
nome = ThisWorkbook.Sheets("Emails").Cells(i, 2).Value
copia = ThisWorkbook.Sheets("Emails").Cells(i, 3).Value
Application.DisplayAlerts = False
Set OutApp = CreateObject("Outlook.Application")
Set outMail = OutApp.CreateItem(olMailItem)
With outMail
.To = destino
If copia <> "" Then
.CC = copia
Else
.CC = ""
End If
.BCC = copyblind
.Subject = nome & ", " & assunto
.Body = mensagem
If anexo <> "" Then
.Attachments.Add (anexo)
End If
.BodyFormat = olFormatHTML
.HTMLBody = "<BODY style=font-size:11pt;font-family:Calibri>" & mensagem & "<BR><BR>" & _
"</BODY>"
.Display
End With
i = i + 1
destino = ThisWorkbook.Sheets("Emails").Cells(i, 1).Value
Set outMail = Nothing
Set OutApp = Nothing
Loop
Application.DisplayAlerts = True
End Sub
Can someone help me?
Try putting HTML tags for a link in the body of your email like so:
Your Hyperlink
I need some help separating a string of email address that I pull from a spreadsheet. I have a sheet set up so when you press the send notification button, the code looks for a number in a set column and if that number is equal to 1 or 2 it pulls the email address from column 4 and inserts it into the "To" field of an email. I would like to log all of those email addresses using the split feature but I keep getting only the first email address and nothing further. Here is my code:
Private Sub CommandButton1_Click()
Dim OutApp As Object
Dim OutMail As Object
Dim strto As String, strcc As String, strbcc As String
Dim strsub As String, strbody As String
Dim emailRng As Range, cl As Range
Dim sTo As String
Dim sCC As String
Dim x As Variant
Dim Y As Variant
Set emailRng = Worksheets("Sheet1").Range("D1:D500")
For Each cl In emailRng
If cl.Offset(, 68) = 1 Then sTo = sTo & ";" & cl.Value
If cl.Offset(, 68) = 2 Then sCC = sCC & ";" & cl.Value
Next cl
sTo = Mid(sTo, 2)
sBCC = Mid(sCC, 2)
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strto = sTo
strcc = sCC
strbcc = ""
strsub = "'NOTIFICATION' - " & Sheet9.Cells(1, 72).Value
strbody = "<img src=Z:\Logo2.jpg width=624 height=74>" & _
"<font size=2 font face=Verdana color=black>"
With OutMail
.SentOnBehalfOfName = ""
.to = strto
.cc = strcc
.bcc = strbcc
.Subject = strsub
.importance = 2
'You can add a file to the mail like this
.HTMLBody = strbody
.Display ' or use .Send
End With
Set OutMail = Nothing
Set OutApp = Nothing
x = Split(sTo, "")
Y = Split(sCC, "")
lrtag = Sheets("Log Sheet").Range("B" & Rows.Count).End(xlUp).Row
Sheets("Log Sheet").Cells(lrtag + 1, "B").Value = "NOTIFICATION SENT"
Sheets("Log Sheet").Cells(lrtag + 1, "C").Value = "DATE SENT"
Sheets("Log Sheet").Cells(lrtag + 1, "D").Value = Now
Sheets("Log Sheet").Cells(lrtag + 1, "E").Value = "NOTIFICATION SENT TO:"
Sheets("Log Sheet").Cells(lrtag + 1, "F").Value =Application.Transpose(x)
Sheets("HEADER").Select
Unload Me
End Sub
I think I need to expand the statement:
Sheets("Log Sheet").Cells(lrtag + 1, "F").Value =Application.Transpose(x)
You don't need to use Transpose if you're placing a single-dimension array in a row, but you do need to specify the full range for the destination:
Sheets("Log Sheet").Cells(lrtag + 1, "F").Resize(1,ubound(x)+1).Value = x
You'd need to use Transpose if you wanted the array to go vertically.
I have VBA code to create pdf file in excel and attache to email on button click. i am wondering if it is possible to attach both pdf and excel file to an email on single click.
please find below code which i am trying to modify.. bold section showing two functions. any suggestion or help greatly appreciated !! Thanks
Sub Button1_Click()
Dim EmailSubject As String, EmailSignature As String
Dim Email_Body As String
Dim olMailItem As Object
'Dim olFormatHTML As Form
Dim objMail As Object
Dim CurrentMonth As String, DestFolder As String, PDFFile As String
Dim Email_To As String, Email_CC As String, Email_BCC As String
Dim OpenPDFAfterCreating As Boolean, AlwaysOverwritePDF As Boolean, DisplayEmail As Boolean
Dim OverwritePDF As VbMsgBoxResult
Dim OutlookApp As Object, OutlookMail As Object
'CurrentMonth = ""
Dim fName As String, eCode1 As String, eCode2 As String, fNameLong As String
' *****************************************************
' ***** You Can Change These Variables *********
'Create excel
fName = "User Access request:"
eCode1 = Sheet1.Range("B7").Value
eCode2 = Range("B7").Value
fNameLong = fName & " " & eCode1 & " - " & eCode2
EmailSubject = "abs" 'Change this to change the subject of the email. The current month is added to end of subj line
OpenPDFAfterCreating = False 'Change this if you want to open the PDF after creating it : TRUE or FALSE
AlwaysOverwritePDF = True 'Change this if you always want to overwrite a PDF that already exists :TRUE or FALSE
DisplayEmail = True 'Change this if you don't want to display the email before sending. Note, you must have a TO email address specified for this to work
Email_To = "abc" 'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
Email_CC = "xyz.com"
Email_BCC = ""
'Create the PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=OpenPDFAfterCreating
**
'Create an Outlook object and new mail message
Set OutlookApp = CreateObject("Outlook.application") 'Dialogs (DialogSendMail).Show ")
Set OutlookMail = OutlookApp.CreateItem(0)
'Create excel file but to another email
Application.Dialogs(xlDialogSendMail).Show "xyz", fNameLong
**
'Display email and specify To, Subject, etc
With OutlookMail
.Display
.To = Email_To
.Cc = Email_CC
.BCC = Email_BCC
.Subject = EmailSubject & CurrentMonth
.Attachments.Add PDFFile
If DisplayEmail = False Then
.Send
End If
End With
End Sub
With OutlookMail
.Display
.To = Email_To
.Cc = Email_CC
.BCC = Email_BCC
.Subject = EmailSubject & CurrentMonth
.Attachments.Add PDFFile
.Attachments.Add "[Excel File Path Goes Here]" 'Add this line
If DisplayEmail = False Then
.Send
End If
End With